当前位置:网站首页>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)
}
}
}
边栏推荐
- Download address collection of various versions of devaexpress
- SQL create temporary table
- Topic | synchronous asynchronous
- 最全SQL与NoSQL优缺点对比
- 【MySQL 12】MySQL 8.0.18 重新初始化
- 技术干货|昇思MindSpore算子并行+异构并行,使能32卡训练2420亿参数模型
- Es writing fragment process
- 技术干货|昇思MindSpore NLP模型迁移之Roberta ——情感分析任务
- Circuit, packet and message exchange
- Lucene hnsw merge optimization
猜你喜欢
Technical dry goods Shengsi mindspire innovation model EPP mvsnet high-precision and efficient 3D reconstruction
截图工具Snipaste
Lucene introduces NFA
[mindspire paper presentation] summary of training skills in AAAI long tail problem
Inverted chain disk storage in Lucene (pfordelta)
Why is data service the direction of the next generation data center?
PAT甲级 1028 List Sorting
【MySQL 14】使用DBeaver工具远程备份及恢复MySQL数据库(Linux 环境)
PAT甲级 1030 Travel Plan
Map interface and method
随机推荐
Shengsi mindspire is upgraded again, the ultimate innovation of deep scientific computing
Introduction of buffer flow
圖像識別與檢測--筆記
Lucene introduces NFA
Lombok cooperates with @slf4j and logback to realize logging
论文学习——鄱阳湖星子站水位时间序列相似度研究
What did the DFS phase do
Partage de l'expérience du projet: mise en œuvre d'un pass optimisé pour la fusion IR de la couche mindstore
Paper learning -- Study on the similarity of water level time series of Xingzi station in Poyang Lake
TCP cumulative acknowledgement and window value update
项目经验分享:基于昇思MindSpore实现手写汉字识别
The babbage industrial policy forum
JS monitors empty objects and empty references
Dora (discover offer request recognition) process of obtaining IP address
Visit Google homepage to display this page, which cannot be displayed
[set theory] Stirling subset number (Stirling subset number concept | ball model | Stirling subset number recurrence formula | binary relationship refinement relationship of division)
技术干货|昇思MindSpore NLP模型迁移之Roberta ——情感分析任务
Vertx multi vertical shared data
Collector in ES (percentile / base)
TreeMap