dtp19819 2014-04-28 19:30
浏览 11
已采纳

在新的声明中设置值

Is it possible to include values in the declaration of a new type.

type Vertex struct {
    X, Y int
}

func main() {
    v := new( Vertex{ 0, 0} ) // Like so
    fmt.Println( v )
    // Instead of :
    v = new(Vertex) 
    v.X, v.Y = 12, 4 // extra line for initializing the values of X and Y 

    fmt.Println( v )
}

Or because go makes the "Vertex{val, val} " a literal value instead of a basic Vertex type it's not possible?

  • 写回答

1条回答 默认 最新

  • duanjia7607 2014-04-28 19:43
    关注

    You don't actually need "new", you can simply write:

    v := Vertex{1,2}
    

    If you want a struct with all members set to the zero value of their types (e.g., 0 for ints, nil for pointers, "" for strings, etc.), it's even simpler:

    v := Vertex{} // same as Vertex{0,0}
    

    You can also only initialize some of the members, leaving the others with their zero value:

    v := Vertex{Y:1} // same as Vertex{0,1}
    

    Note that with these v will be a variable of type Vertex. If you want a pointer to a Vertex, use:

    v := &Vertex{1,2}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看