Go中的面向对象编程-使用“ new”关键字还是不?

I am learning Go, and I have a question based on the following code:

package main

import (
    "fmt"
)

type Vector struct {
    x, y, z int
}

func VectorFactory(x,y,z int) *Vector {
    return &Vector{x, y, z}
}

func main() {
    vect := VectorFactory(1, 2, 3)
    fmt.Printf("%d
", (vect.x * vect.y * vect.z))
}

Here I've defined a type Vector with x, y, and z, and I've defined function VectorFactory which declares a pointer to a Vector and returns that pointer. I use this function to create a new Vector named vect.

  • Is this bad code? Should I be using the new keyword rather than building a Factory?
  • Do I need to delete the Vector after using it, like in C++? If so, how?

Thanks. I'm still waiting for my Go book to be delivered.

Prefer NewThing to ThingFactory.

Don't make a NewThing function, unless you have complex initialisation, or you're intentionally not exporting parts of a struct. Selectively setting only parts of a struct is not complex, that can be accomplished by using labels. Complex would be things like "the value of slot Q depends on what the value of slot Zorb is". Unexported struct fields can be useful for information hiding, but should be used with care.

Go is garbage-collected, any piece of data that is not referenced is eligible to be collected. Start out y not worrying about it, then get to a point where you ensure you clean up any reference to data you're no longer interested in so as to avoid accidental liveness ("accidental liveness" is essentially the GC equivalent of "memory leak").

If you expect to print your data structures frequently, consider making a String method for them (this is not exactly corresponding to the print you do, but might be generally more useful for a vector):

func (v Vector) String() string {
  return fmt.Sprintf("V<%d, %d, %d>", v.x v.y, v.z);
}

Unless "vect" really means something to you, prefer either "v" or "vector" as a name.