Go 语言提倡面向接口编程,一来增强代码的可读性,二来可以使代码的模块之间的关系变得更加清晰、边界更加明显。
接口也是一个数据类型,该类型使用结构 interface{...} 来定义
只要有类实现(模拟)了接口中包含的所有方法,我们就称这个类型实现了这个接口
只要是实现了这个接口的类型,用这个类型定义的变量就可以给这个接口声明的变量赋值
以上两个特性也可以推出 interface{} 类型的变量,可以接收 任何变量的赋值
package main
import "fmt"
var stuInterface interface {
PrintAge()
}
type Student struct {
Name string
Age int
}
func (s Student) PrintAge() {
fmt.Println(s.Age)
}
func main() {
stuInterface = Student{
Name: "Codey",
Age: 18,
}
stuInterface.PrintAge()
}
18
一般都会使用自定义类型来定义一个接口类型。同时还可以写一个函数来实例化接口
package main
import "fmt"
type StudentInterface interface {
PrintAge()
}
type Student struct {
Name string
Age int
}
func (s Student) PrintAge() {
fmt.Println(s.Age)
}
func newStudent(name string, age int) StudentInterface {
return Student{Name: name, Age: age}
}
func main() {
stuInterface := newStudent("Codey", 18)
stuInterface.PrintAge()
}
18
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。