首页  

GO结构体三种初始化方式     所属分类 go 浏览量 672
t := new(T)  t为指向该结构体的指针

var t T 

字面量方式

t := T{a, b} 
t := &T{} //等效于 new(T)


package main

import "fmt"

func main() {
   
   pet1 := new(Pet)
   // *main.Pet ,&{0 }
   fmt.Printf("%T ,%v\n",pet1,pet1)
   var pet2 Pet
   // main.Pet ,{0 }
   fmt.Printf("%T ,%v\n",pet2,pet2)
   pet3 := Pet{1, "cat"} 
   // main.Pet ,{1 cat}
   fmt.Printf("%T ,%v\n",pet3,pet3)   
   // 等效于 new(Pet)
   pet4 := &Pet{}
   // *main.Pet ,&{0 }
   fmt.Printf("%T ,%v\n",pet4,pet4)
   
}

type Pet struct{
  id int
  name string
}

上一篇     下一篇
Java锁升级过程

GO内建函数

GO make 和 new的区别

GO 面向对象编程

GO reflect

GO基础选择题