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?
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}