Golang Interface interface

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Interface interface

    • An interface is a collection of one or more method signatures
    • As long as a type has all of the method signatures for that interface, that is the implementation of that interface without showing which interface the declaration implements, which becomes structural Typing
    • Interfaces are only method declarations, no implementations, no data fields
    • Interfaces can be embedded anonymously in other interfaces, or embedded in a structure
    • When an object is assigned to an interface, a copy occurs, and the interface stores a pointer to the replica that cannot modify the state of the replica or retrieve the pointer
    • The interface is equal to nil only if the interface stores both the type and the object are nil
    • Interface calls do not automatically convert receiver
    • Interface also supports anonymous field methods
    • Interfaces can also be implemented to resemble the polymorphism in OOP
    • An empty interface can be used as a container for any type of data
  Package Mainimport ("FMT") type USB interface {//defines an interface below which contains two methods//name method returns a string Name () string  Connection method Connect ()}type phoneconnecter struct {//Use this struct to implement the USB Interface name String}func (PC Phoneconnecter) name () The string {//implementation interface is a method of implementing interface with this structure, return Pc.name}func (PC Phoneconnecter) Connect () {fmt. Println ("Connect:", Pc.name)}func main () {var a USB///Declare a variable with a type of USB interface A = Phoneconnect er{"Phoneconnecter"}//Here is a USB type, it cannot be taken to name this field A.connect ()}  
package mainimport (    "fmt")type USB interface { //定义一个接口,这个接口下面包含两个方法    //Name方法返回一个字符串    Name() string    //连接的方法    Connect()}type PhoneConnecter struct { //用这个struct对这个USB的接口进行实现    name string}func (pc PhoneConnecter) Name() string { //实现接口就是用这个结构,实现interface的方法    return pc.name}func (pc PhoneConnecter) Connect() {    fmt.Println("Connect:", pc.name)}func main() {    // var a USB                            //声明一个变量,它的类型是USB接口    a := PhoneConnecter{"PhoneConnecter"} //这里的a是usb类型的,它无法去到name 这个字段    a.Connect()    Disconnect(a) //这里我们将a传进去,会发现a就是USB类型的}func Disconnect(usb USB) { // 这里传进去的要求,类型必须是USB的这个接口    fmt.Println("Disconnected.")}

Embedded interface

package mainimport (    "fmt")type Connecter interface {    Connect()}type USB interface { //定义一个接口,这个接口下面包含两个方法    //Name方法返回一个字符串    Name() string    Connecter //这里将connecter的接口嵌入到USB当中}type PhoneConnecter struct { //用这个struct对这个USB的接口进行实现    name string}func (pc PhoneConnecter) Name() string { //实现接口就是用这个结构,实现interface的方法    return pc.name}func (pc PhoneConnecter) Connect() {    fmt.Println("Connect:", pc.name)}func main() {    // var a USB                            //声明一个变量,它的类型是USB接口    a := PhoneConnecter{"PhoneConnecter"} //这里的a是usb类型的,它无法去到name 这个字段    a.Connect()    Disconnect(a) //这里我们将a传进去,会发现a就是USB类型的,所以可以验证PhoneConnecter实现USB的接口}func Disconnect(usb USB) { // 这里传进去的要求,类型必须是USB的这个接口    fmt.Println("Disconnected.")}

Data types in an interface can be judged by the type assertion's OK pattern

package mainimport (    "fmt")type Connecter interface {    Connect()}type USB interface { //定义一个接口,这个接口下面包含两个方法    //Name方法返回一个字符串    Name() string    Connecter}type PhoneConnecter struct { //用这个struct对这个USB的接口进行实现    name string}func (pc PhoneConnecter) Name() string { //实现接口就是用这个结构,实现interface的方法    return pc.name}func (pc PhoneConnecter) Connect() {    fmt.Println("Connect:", pc.name)}func main() {    // var a USB                            //声明一个变量,它的类型是USB接口    a := PhoneConnecter{"PhoneConnecter"} //这里的a是usb类型的,它无法去到name 这个字段    a.Connect()    Disconnect(a) //这里我们将a传进去,会发现a就是USB类型的,所以可以验证PhoneConnecter实现USB的接口}func Disconnect(usb USB) { // 这里传进去的要求,类型必须是USB的这个接口    if pc, ok := usb.(PhoneConnecter); ok {        fmt.Println("Disconnected.", pc.name)        return    }    fmt.Println("Unknow device.")}//go语言当中任何类型都实现了空接口

The go language has an empty interface for any type

package mainimport (    "fmt")type Connecter interface {    Connect()}type USB interface { //定义一个接口,这个接口下面包含两个方法    //Name方法返回一个字符串    Name() string    Connecter}type PhoneConnecter struct { //用这个struct对这个USB的接口进行实现    name string}func (pc PhoneConnecter) Name() string { //实现接口就是用这个结构,实现interface的方法    return pc.name}func (pc PhoneConnecter) Connect() {    fmt.Println("Connect:", pc.name)}func main() {    // var a USB                            //声明一个变量,它的类型是USB接口    a := PhoneConnecter{"PhoneConnecter"} //这里的a是usb类型的,它无法去到name 这个字段    a.Connect()    Disconnect(a) //这里我们将a传进去,会发现a就是USB类型的,所以可以验证PhoneConnecter实现USB的接口}func Disconnect(usb interface{}) { // 这里把USB替换成空接口    if pc, ok := usb.(PhoneConnecter); ok {        fmt.Println("Disconnected.", pc.name)        return    }    fmt.Println("Unknow device.")}

Use type switch to make a more comprehensive type judgment on an empty interface

package mainimport (    "fmt")type Connecter interface {    Connect()}type USB interface { //定义一个接口,这个接口下面包含两个方法    //Name方法返回一个字符串    Name() string    Connecter}type PhoneConnecter struct { //用这个struct对这个USB的接口进行实现    name string}func (pc PhoneConnecter) Name() string { //实现接口就是用这个结构,实现interface的方法    return pc.name}func (pc PhoneConnecter) Connect() {    fmt.Println("Connect:", pc.name)}func main() {    // var a USB                            //声明一个变量,它的类型是USB接口    a := PhoneConnecter{"PhoneConnecter"} //这里的a是usb类型的,它无法去到name 这个字段    a.Connect()    Disconnect(a) //这里我们将a传进去,会发现a就是USB类型的,所以可以验证PhoneConnecter实现USB的接口}func Disconnect(usb interface{}) { // 这里把USB替换成空接口    switch v := usb.(type) {    case PhoneConnecter:        fmt.Println("Disconnected.", v.name)    default:        fmt.Println("Unknow device.")    }}

Mutual conversion of interfaces

package mainimport (    "fmt")type Connecter interface {    Connect()}type USB interface { //定义一个接口,这个接口下面包含两个方法    //Name方法返回一个字符串    Name() string    Connecter}type PhoneConnecter struct { //用这个struct对这个USB的接口进行实现    name string}func (pc PhoneConnecter) Name() string { //实现接口就是用这个结构,实现interface的方法    return pc.name}func (pc PhoneConnecter) Connect() {    fmt.Println("Connect:", pc.name)}func main() {    pc := PhoneConnecter{"PhoneConnecter"}    var a Connecter    a = Connecter(pc) //这里的a是强制类型转换,将pc转换成了Connecter接口    a.Connect()       //这里可以看到接口的转换,只能由超级转换成子集}//可以将拥有超集的接口转换为子集的接口func Disconnect(usb interface{}) { // 这里把USB替换成空接口    switch v := usb.(type) {    case PhoneConnecter:        fmt.Println("Disconnected.", v.name)    default:        fmt.Println("Unknow device.")    }}

When assigning an object to an interface, a copy occurs, and the interface internally stores a pointer to the
A pointer to a replica that can neither modify the state of the replica nor get a pointer

  Package Mainimport ("FMT") type Connecter interface {Connect ()}type USB Interface {//define an interface with two parties below this interface The//name method returns a string name () string Connecter}type phoneconnecter struct {//using this struct to implement the USB interface name String}fu     NC (PC Phoneconnecter) Name () string {//Implement interface is using this structure, implement interface method return Pc.name}func (PC Phoneconnecter) Connect () { Fmt. Println ("Connect:", Pc.name)}func main () {pc: = phoneconnecter{"Phoneconnecter"} var a connecter a = Connecter (p c) A.connect () pc.name = "PC"//When the object is assigned to the interface, a copy occurs, and the interface stores a pointer to the replica, FMT. PRINTLN (Pc.name)//Can neither modify the status of the replica nor get the pointer A.connect ()}func Disconnect (USB interface{}) {//here replace the USB with an empty interface switch V: = us B. (type) {case phoneconnecter:fmt. Println ("Disconnected.", V.name) default:fmt.    PRINTLN ("Unknow device.") }}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.