dongtaogou6226 2014-01-06 01:39
浏览 26

开始,这是您分配和初始化所需了解的所有内容吗?

It is just mind boggling how many different ways Go has for variable initialization. May be either i don't understand this completely or Go is a big after thought. Lot of things don't feel natural and looks like they added features as they found them missing. Initialization is one of them.

Here is running app on Go playground showing different ways of initialization

Here is what i understand

  1. There are values and pointers. Values are initiated using var = or :=.
  2. := only works inside the methods
  3. To Create value and reference you use new or &. And they only work on composite types.
  4. There are whole new ways of creating maps and slices
  5. Create slice and maps using either make or var x []int. Noticing there is no = or :=

Are there any easy way to understand all this for newbies? Reading specs gives all this in bits and pieces everywhere.

  • 写回答

3条回答 默认 最新

  • dongtuo4723 2014-01-06 02:00
    关注

    Yeah, this was one of those things that I found confusing early as well. I've come up with my own rules of thumb which may or may not be best practices, but they've served me well. Tweaked after comment from Stephen about zero values

    1. Use := as much as possible, let Go infer types
    2. If you just need an empty slice or map (and don't need to set an initial capacity), use {} syntax

      s := []string{}
      m := map[string]string{}

    3. The only reason to use var is to initialize something to a zero value (pointed out by Stephen in comments) (and yeah, outside of functions you'll need var or const as well):

      var ptr *MyStruct // this initializes a nil pointer
      var t time.Time // this initializes a zero-valued time.Time

    评论

报告相同问题?

悬赏问题

  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序