golang结构体没有构造函数,可以使用工厂模式来解决这个问题
结构体名称首字母是小写时,外部就无法引用,用工厂模式来解决
package model
// 首字母大写
type Student struct {
Name string
Score int
}
package model
// 首字母小写
type teacher struct {
name string
}
func NewStudent(n string) *teacher {
return &teacher{
name: n,
}
}
package main
import (
"fmt"
"gitee/shang/awesomeProject/model"
)
func main() {
//Student首字母大写,可以直接用
var student = model.Student{
Name: "admin",
Score: 10,
}
fmt.Printf("student:%v\n", student)
// teacher首字母小写,通过工厂模式来使用
var teacher = model.NewStudent("Tom")
fmt.Printf("teacher:%v\n", *teacher)
}