当前位置:网站首页>Go language foundation ----- 08 ----- interface
Go language foundation ----- 08 ----- interface
2022-07-03 07:37:00 【Mango sauce】
1 Interface type introduction
An interface is an abstract type , It will not expose the structure of the internal values of the object it represents and the basic operations supported by this object , It will only show their own way , Because interface types cannot be instantiated .
2 Interface definition and implementation
- 1) Interface names are generally er The ending is named , for example Windowser.
- 2) Interfaces have only method declarations , It didn't come true , No data fields .
- 3) Interfaces can be embedded anonymously into other interfaces , Or embedded in the structure .
package main
import "fmt"
// Definition of interface
type Humaner interface {
// Method , Only the statement , It didn't come true , By other types
sayhi()
}
type Student struct {
name string
id int
}
func (t *Student) sayhi(){
fmt.Printf("Student[%s, %d], sayhi\n", t.name, t.id)
}
type Teacher struct {
addr string
group string
}
func (t *Teacher) sayhi(){
fmt.Printf("Teacher[%s, %s], sayhi\n", t.addr, t.group)
}
type MyStr string
func (t *MyStr) sayhi(){
fmt.Printf("MyStr[%s], sayhi\n", *t)
}
func main(){
// 1. Define the interface variable , The value is implemented by The methods in this interface Type assignment of
var i Humaner
s := &Student{
"hc", 1} // It is a pointer because the receiver of the method implemented by the interface is a pointer .
i = s
i.sayhi()
t := &Teacher{
"hc", "www"}
i = t
i.sayhi()
var m MyStr = "hc"
//m := "hc" // In this way , It can lead to i = &m error , Because the automatic derivation type will be string, instead of MyStr,
// So there won't be sayhi Method . Even if MyStr Namely string type , But the compiler thinks MyStr And string It's a different type .
i = &m
i.sayhi()
}

3 The manifestation of polymorphism
Polymorphism is that the same interface can show a variety of forms .
package main
import "fmt"
// Definition of interface
type Humaner interface {
// Method , Only the statement , It didn't come true , By other types
sayhi()
}
type Student struct {
name string
id int
}
func (t *Student) sayhi(){
fmt.Printf("Student[%s, %d], sayhi\n", t.name, t.id)
}
type Teacher struct {
addr string
group string
}
func (t *Teacher) sayhi(){
fmt.Printf("Teacher[%s, %s], sayhi\n", t.addr, t.group)
}
type MyStr string
func (t *MyStr) sayhi(){
fmt.Printf("MyStr[%s], sayhi\n", *t)
}
// Define an ordinary function , Formal parameters are interface types ,
// This makes a function , But there are different behaviors , That is polymorphism
func WhoSayHi(i Humaner){
i.sayhi()
}
func main(){
s := &Student{
"hc", 1}
t := &Teacher{
"hc", "www"}
var m MyStr = "hc"
WhoSayHi(s)
WhoSayHi(t)
WhoSayHi(&m)
// Or you can write
arr := make([]Humaner, 3)
arr[0] = s
arr[1] = t
arr[2] = &m
for _, v := range arr{
v.sayhi()
}
}

4 Inheritance of interfaces
package main
import "fmt"
// Definition of interface
// A subset of , Equivalent to base class
type Humaner interface {
// Method , Only the statement , It didn't come true , By other types
sayhi()
}
// Superset , Equivalent to a derived class
type Persioner interface {
Humaner // Anonymous field , Inherited interface , So the top sayhi There will also be methods
sing(t string)
}
type Student struct {
name string
id int
}
func (t *Student) sayhi(){
fmt.Printf("Student[%s, %d], sayhi\n", t.name, t.id)
}
func (t *Student) sing(s string){
fmt.Printf("Student sing %s\n", s)
}
func main(){
// 1. Define the interface variable , The value is implemented by The methods in this interface Type assignment of
var i Persioner
s := &Student{
"hc", 1} // It is a pointer because the receiver of the method implemented by the interface is a pointer .
i = s
i.sayhi()
i.sing("lqq")
}

5 Interface conversion
The conversion of interfaces is just the conversion of supersets and subsets , Superset refers to the inherited interface , Subset refers to the inherited interface . contrast C++, Subsets are equivalent to base classes , Supersets are equivalent to derived classes . So there is :
- 1) Supersets can be converted into subsets , Subsets cannot be converted into supersets . Did you learn C++ We know , This is because when a subset is converted to a superset, the address will be out of bounds , Unable to address to the corresponding memory .
package main
import "fmt"
// Definition of interface
// A subset of , Equivalent to base class
type Humaner interface {
// Method , Only the statement , It didn't come true , By other types
sayhi()
}
// Superset , Equivalent to a derived class
type Persioner interface {
Humaner // Anonymous field , Inherited interface , So the top sayhi There will also be methods
sing(t string)
}
type Student struct {
name string
id int
}
func (t *Student) sayhi(){
fmt.Printf("Student[%s, %d], sayhi\n", t.name, t.id)
}
func (t *Student) sing(s string){
fmt.Printf("Student sing %s\n", s)
}
func main(){
// Supersets can be converted into subsets , Subsets cannot be converted into supersets .
var iPro Persioner // Superset
iPro = &Student{
"hc", 1}
var i Humaner // A subset of
i = iPro // ok
i.sayhi()
//iPro = i // err:cannot use i (type Humaner) as type Persioner in assignment:
// Humaner does not implement Persioner (missing sing method)
}

6 Empty interface
- 1) Empty interface (interface{}) There's no way , Because of that , So any type implements an empty interface . Because an empty interface can store any type of assignment , similar C/C++ Of void*.
var i interface{
} = 1
fmt.Printf("i = %d\n", i)
i = "abc"
fmt.Printf("i = %s\n", i)
- 2) When a function wants to receive any type of parameter , Then the formal parameter can be defined as an empty interface . The most typical is the standard library fmt Of Printxxx Class function . For example, simply list two :
func Println(a ...interface{
}) (n int, err error)
func Printf(format string, a ...interface{
}) (n int, err error)
7 Types of queries ( Also called type assertion )
Here are two ways to achieve .
- 1) adopt if Implement type query .
- 2) adopt switch Implement type query .
package main
import (
"fmt"
)
// Definition of interface
// A subset of , Equivalent to base class
type Humaner interface {
// Method , Only the statement , It didn't come true , By other types
sayhi()
}
// Superset , Equivalent to a derived class
type Persioner interface {
Humaner // Anonymous field , Inherited interface , So the top sayhi There will also be methods
sing(t string)
}
type Student struct {
name string
id int
}
func (t *Student) sayhi(){
fmt.Printf("Student[%s, %d], sayhi\n", t.name, t.id)
}
func (t *Student) sing(s string){
fmt.Printf("Student sing %s\n", s)
}
func main(){
i := make([]interface{
}, 3)
i[0] = 1
i[1] = "hhh"
i[2] = Student{
"hc", 1}
// Types of queries ( Types of assertions )
// 1. if Realization
for k, v := range i{
if value, ok := v.(int); ok == true {
fmt.Printf("x[%d], The type is int, The content is : %d\n", k, value)
}else if value, ok := v.(string); ok == true{
fmt.Printf("x[%d], The type is string, The content is : %s\n", k, value)
}else if value, ok := v.(Student); ok == true{
fmt.Printf("x[%d], The type is Student, The content is : name=%s, id=%d\n", k, value.name, value.id)
}
}
// 2. switch Realization
for k, v := range i{
switch value := v.(type) {
case int:
fmt.Printf("x[%d], The type is int, The content is : %d\n", k, value)
case string:
fmt.Printf("x[%d], The type is string, The content is : %s\n", k, value)
case Student:
fmt.Printf("x[%d], The type is Student, The content is : name=%s, id=%d\n", k, value.name, value.id)
}
}
}

边栏推荐
- Lucene hnsw merge optimization
- 【LeetCode】2. Valid Parentheses·有效的括号
- Robots protocol
- Jeecg request URL signature
- 【MySQL 14】使用DBeaver工具远程备份及恢复MySQL数据库(Linux 环境)
- TCP cumulative acknowledgement and window value update
- Mail sending of vertx
- Summary of Arduino serial functions related to print read
- HCIA notes
- VMware virtual machine installation
猜你喜欢

技术干货|昇思MindSpore NLP模型迁移之Roberta ——情感分析任务

IO stream system and FileReader, filewriter

技术干货|AI框架动静态图统一的思考

Technical dry goods Shengsi mindspire lite1.5 feature release, bringing a new end-to-end AI experience

Project experience sharing: Based on mindspore, the acoustic model is realized by using dfcnn and CTC loss function

圖像識別與檢測--筆記

IPv4 address
![[set theory] Stirling subset number (Stirling subset number concept | ball model | Stirling subset number recurrence formula | binary relationship refinement relationship of division)](/img/d8/b4f39d9637c9886a8c81ca125d6944.jpg)
[set theory] Stirling subset number (Stirling subset number concept | ball model | Stirling subset number recurrence formula | binary relationship refinement relationship of division)

图像识别与检测--笔记

How long is the fastest time you can develop data API? One minute is enough for me
随机推荐
The babbage industrial policy forum
论文学习——鄱阳湖星子站水位时间序列相似度研究
技术干货|AI框架动静态图统一的思考
技术干货|昇思MindSpore NLP模型迁移之LUKE模型——阅读理解任务
Mail sending of vertx
The underlying mechanism of advertising on websites
Jeecg request URL signature
HarmonyOS第三次培训笔记
opensips与对方tls sip trunk对接注意事项
【MySQL 13】安装MySQL后第一次修改密码,可以可跳过MySQL密码验证进行登录
An overview of IfM Engage
Shengsi mindspire is upgraded again, the ultimate innovation of deep scientific computing
[set theory] Stirling subset number (Stirling subset number concept | ball model | Stirling subset number recurrence formula | binary relationship refinement relationship of division)
项目经验分享:实现一个昇思MindSpore 图层 IR 融合优化 pass
Various postures of CS without online line
Leetcode 198: 打家劫舍
【LeetCode】4. Best Time to Buy and Sell Stock·股票买卖最佳时机
Some basic operations of reflection
Longest common prefix and
TCP cumulative acknowledgement and window value update