1. 声明一个 interface
type UserInterface interface {
SetInfo(username string, age int)
GetUsername() (username string)
GetAge() (age int)
}
2. 创建一个 实现了 User
interface 的结构
type User struct {
Username string
Age int
}
func (t *User) SetInfo(username string, age int) {
t.Username = username
t.Age = age
}
func (t *User) GetUsername() (username string) {
return t.Username
}
func (t *User) GetAge() (age int) {
return t.Age
}
3. 如何使用
// 假设一个函数需要 UserInterface 类型
func GetUser(user UserInterface) {
user.SetInfo("Tom")
fmt.Println(user.GetUsername())
fmt.Println(user.GetAge())
}
// 调用
GetUser(new(User))
4. 总结
在go中如果一个结构体实现了 interface 中约定的函数那么这个 结构体 就可以 使用在 这个 interface 中
PS: 使用时 这个 User
必须以指针方式传入
评论区