• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Go 和amp;T{}和new(T)和(*T)(nil)区别

武飞扬头像
@子非鱼
帮助3

  • (* T)(nil) 它返回nil指针或没有指针,但仍然为struct的所有字段分配内存。
  • new(T)和& T {} 完全等价:分配一个零T并返回一个指向这个分配的内存的指针。唯一的区别是,& T {} 不适用于内置类型,如 int ;你只能做 new(int)。
  1.  
    package main
  2.  
     
  3.  
    import (
  4.  
    "fmt"
  5.  
    )
  6.  
     
  7.  
    type Struct struct {
  8.  
    Field int
  9.  
    }
  10.  
     
  11.  
    func main() {
  12.  
    test1 := &Struct{}
  13.  
    test2 := new(Struct)
  14.  
    test3 := (*Struct)(nil)
  15.  
    fmt.Printf("%#v, %#v, %#v \n", test1, test2, test3) //&main.Struct{Field:0}, &main.Struct{Field:0}, (*main.Struct)(nil)
  16.  
     
  17.  
    fmt.Printf("%T, %T, %T \n", test1, test2, test3) // *main.Struct, *main.Struct, *main.Struct
  18.  
     
  19.  
    test1.Field = 1
  20.  
    fmt.Println(test1.Field) // 1
  21.  
     
  22.  
    test2.Field = 2
  23.  
    fmt.Println(test2.Field) // 2
  24.  
     
  25.  
    test3.Field = 3 // test3分配内存,返回一个nil指针,不能使用
  26.  
    // fmt.Println(test3.Field)
  27.  
    }
学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhfhiihe
系列文章
更多 icon
同类精品
更多 icon
继续加载