douyongdao4046 2015-11-18 19:36
浏览 69
已采纳

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.

  • 写回答

1条回答 默认 最新

  • doujue1246 2015-11-19 10:13
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?