跳到主要内容

模拟构造函数

Go语言没有构造函数,但是我们可以使用结构体初始化的过程来模拟实现构造函数。

package main

import "fmt"

type Student struct {
sid int
name string
age int8
course []string // 选秀课程
}

func NewStudent(sid int, name string, age int8, course []string) *Student {
return &Student{
sid: sid,
name: name,
age: age,
course: course,
}
}

func main() {
s := NewStudent(1001, "yuan", 32, nil)
fmt.Println(s)
}