网站建设深,网站没收录,物流企业的网站模板,wordpress添加磁力下载一、结构体基础
1.1 结构体定义
// 基本结构体定义
type Person struct {Name stringAge intEmail stringAddress Address // 嵌套结构体
}// 匿名结构体
var user struct {ID intName string
}1.2 结构体声明与初始化
// 方法1#xff1a;使用字段名初始化
p1 : …一、结构体基础1.1 结构体定义// 基本结构体定义typePersonstruct{NamestringAgeintEmailstringAddress Address// 嵌套结构体}// 匿名结构体varuserstruct{IDintNamestring}1.2 结构体声明与初始化// 方法1使用字段名初始化p1:Person{Name:张三,Age:30,Email:zhangsanexample.com,}// 方法2按顺序初始化必须包含所有字段p2:Person{李四,25,lisiexample.com,Address{}}// 方法3零值初始化varp3 Person// 所有字段为零值// 方法4使用newp4:new(Person)// 返回指针(*p4).Name王五p4.Name王五// 简写Go自动解引用二、结构体高级特性2.1 嵌套与匿名嵌套typeAddressstruct{CitystringStreetstringZipCodestring}typeCompanystruct{NamestringAddress Address// 具名嵌套}typeEmployeestruct{NamestringAgeintAddress// 匿名嵌套嵌入}funcmain(){emp:Employee{Name:张三,Age:30,Address:Address{City:北京,Street:朝阳路,ZipCode:100000,},}// 直接访问嵌入字段fmt.Println(emp.City)// 北京fmt.Println(emp.Address.City)// 同上}2.2 结构体标签Tagsimportencoding/jsontypeUserstruct{IDintjson:id db:user_idUsernamestringjson:username db:usernamePasswordstringjson:-// 不序列化Emailstringjson:email,omitempty// 空值时不序列化}funcmain(){user:User{ID:1,Username:alice,Password:secret,}// JSON 序列化data,_:json.Marshal(user)fmt.Println(string(data))// {id:1,username:alice}}2.3 结构体方法typeRectanglestruct{Widthfloat64Heightfloat64}// 值接收者方法操作副本func(r Rectangle)Area()float64{returnr.Width*r.Height}// 指针接收者方法可修改原值func(r*Rectangle)Scale(factorfloat64){r.Width*factor r.Height*factor}// 方法调用rect:Rectangle{Width:10,Height:5}area:rect.Area()// 50rect.Scale(2)// Width20, Height10三、结构体组合与接口3.1 组合实现继承typeAnimalstruct{NamestringAgeint}func(a*Animal)Speak(){fmt.Println(Animal speaks)}typeDogstruct{Animal// 嵌入AnimalBreedstring}func(d*Dog)Bark(){fmt.Println(Woof!)}funcmain(){dog:Dog{Animal:Animal{Name:Buddy,Age:3},Breed:Golden Retriever,}dog.Speak()// Animal speaksdog.Bark()// Woof!fmt.Println(dog.Name)// Buddy}3.2 结构体实现接口typeShapeinterface{Area()float64Perimeter()float64}typeCirclestruct{Radiusfloat64}func(c Circle)Area()float64{returnmath.Pi*c.Radius*c.Radius}func(c Circle)Perimeter()float64{return2*math.Pi*c.Radius}funcPrintShapeInfo(s Shape){fmt.Printf(面积: %.2f, 周长: %.2f\n,s.Area(),s.Perimeter())}四、实用技巧与模式4.1 工厂函数模式typeConfigstruct{hoststringportinttimeout time.Duration}// 私有字段使用工厂函数funcNewConfig(hoststring,portint)*Config{returnConfig{host:host,port:port,timeout:30*time.Second,// 默认值}}func(c*Config)WithTimeout(timeout time.Duration)*Config{c.timeouttimeoutreturnc}4.2 结构体比较typePointstruct{X,Yint}funcmain(){p1:Point{1,2}p2:Point{1,2}p3:Point{2,3}fmt.Println(p1p2)// truefmt.Println(p1p3)// false// 包含不可比较字段如slice的结构体不能比较typeBadStructstruct{data[]int}// b1 b2 // 编译错误}4.3 空结构体// 零内存占用用作标记或map的键typeemptystruct{}varsignalstruct{}{}// 用作Set的键typeSetmap[string]struct{}func(s Set)Add(keystring){s[key]struct{}{}}func(s Set)Contains(keystring)bool{_,ok:s[key]returnok}4.4 内存对齐与优化// 不良的内存布局typeBadLayoutstruct{bbool// 1字节iint64// 8字节sstring// 16字节b2bool// 1字节}// 总大小约32字节包含填充// 优化的内存布局按大小排序typeGoodLayoutstruct{sstring// 16字节iint64// 8字节bbool// 1字节b2bool// 1字节}// 总大小约24字节funcmain(){fmt.Println(unsafe.Sizeof(BadLayout{}))// 32fmt.Println(unsafe.Sizeof(GoodLayout{}))// 24}六、总结使用工厂函数提供清晰的对象创建方式小写不可导出字段通过方法控制访问合理使用指针接收者需要修改接收者时结构体较大时避免复制保持一致性要么全用指针要么全用值利用结构体标签简化序列化/反序列化注意内存布局对性能敏感的结构体进行字段重排组合优于继承使用嵌入实现代码复用实现常用接口如Stringer,error等