背景:当结构体名的首字母为小写时,这时这个结构体只能在本包使用,而不能被其他包使用,
但是在别的包中又希望可以使用这个结构体。由于go语言中没有构造函数,可以使用工厂模式来解决这个问题。
举例:model包中student结构体首字母为小写,main包中需使用student结构体
student.go
package model type student struct { Name string Score float32 } func NewStudent(name string, score float32) *student { return &student{ Name: name, Score: score, } }
main.go
package main import ( "fmt" "model" ) func main() { student := model.NewStudent("小明", 90.5) fmt.Println("student=", *student) }
当student结构体中Score字段首字母修改为小写score时,如何在main包中重新给Score字段赋值
student.go
package model type student struct { Name string score float32 } func NewStudent(name string, score float32) *student { return &student{ Name: name, score: score, } } func (stu *student) GetScore() float32 { return stu.score } func (stu *student) SetScore(s float32) { stu.score = s }
main.go
package main import ( "fmt" "model" ) func main() { student := model.NewStudent("小明", 90.5) fmt.Println("student=", *student) student.SetScore(100) fmt.Println("student.Name=", student.Name, "student.score=", student.GetScore()) }