Go method, interface

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

In Go, a type can define a function that receives this type, that is, a method. Each type has an interface, which means that a collection of methods is defined for that type.

The following defines the struct type S and its two methods:

typestructint }funcintreturn p.i }funcint) { p.i = v }

Method

The method is to have the receiver's function.

You can define methods on any type except for non-native types, including built-in types, such as int. However, you can define an alias for the built-in type, and then you can define the method for the alias. Such as

int// 为 int 定义别名 Foofunc (self Foo) Emit() {    fmt.Printf("%v"self)}

Interface

An interface is defined as a collection of methods. Method contains the actual code. In other words, an interface is defined, and the method is implemented. Therefore, the receiver cannot be defined as an interface type, and doing so will cause invalid receiver type ... Compiler error.

Authoritative content from the language specification:

The recipient type must be T or *t, where T is the type name. T is called the recipient base type or short base type. The underlying type must not be a pointer or interface type, and is defined in the same package as the method.

// 定义了有两个方法的接口 I,结构 S 实现了此接口typeinterface {    int    int)}

You can define a variable (interface value) of an interface type as an argument to a function, and a variable of the type that implements the interface can be passed as an argument to the interface variable and its method is called.

func f(p I) {    fmt.Println(p.Get())    p.Put(1)}var// S 类型的变量 s 作为实参传给接口。取地址是因为在 s 的指针上定义了方法,这样可以修改 s;      // 如果在 s 上定义方法,则修改的只是 s 的副本

It is meaningless to create pointers to interfaces in Go. It is also illegal to create a pointer to an interface value.

Interface type judgment

In go, to determine the type of variable passed to the interface value, it can be obtained using type switch. (type) can only be switch used in.

//Another implementation of the I interface R typetypeRstruct{iint}func(P *r) Get ()int{returnP.I}func(P *r) Put (vint) {p.i = v}funcF (P I) {SwitchT: = P. (type) {//Determine the actual type passed to P         Case*s://pointer type pointing to S         Case*r://pointer type pointing to R         CaseS//S type         CaseR://R type        default://Implements other types of I interfaces}}

To switch determine whether an interface type implements an interface, you can use "comma OK".

value, ok := Interfacevariable.(implementType)

Where the interface Interfacevariable variable (interface value), implementType for implementing the type of this interface, returns the value of the value actual type variable of the interface variable, if that type implements the return of this interface true .

typeinterface// 有一个方法的接口 I    Get() Int}typeint// Int 类型实现了 I 接口func (i Int) Get() Int{    return i}var myint Int = 5var// 变量赋值给接口val, ok := inter.(Int)fmt.Printf("%v, %v"// 输出为:5,true

Null interface

Each type can match to an empty interface: interface{} . An empty interface type has no constraints on the method (because there is no method), it can contain any type, or it can implement conversions to other interface types. If the type variable passed to the interface implements the converted interface, it can run normally, or a run-time error occurs.

funcinterfaceint {    returnnew// (I) 将 si 转换到 I 类型的接口,s 实现了 Get 方法,因此可以调用 g()i := 5// 运行时出错,因为 int 型没有 Get 方法

You can also list another interface in the interface, such as

typeinterface {    // 另一个接口    interface{})    interface{}}

Introspection and reflection

...

copyright notice: This article for Bo Master original article, without Bo Master permission not reproduced.

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.