Go learning notes-types and interfaces

Source: Internet
Author: User

If other content in the go language does not seem to be much different from that in the c/c ++ language, its interface design will be surprising, sometimes it really gives me the illusion that I am using a dynamic language.

Here, the structure type is very similar to the C language. The definition structure is as follows:
type Man struct {     name string     age int}

Declare Structure Variables and initialize them:
Var m Man // declare the Man variable m: = new (Man) // declare a Man pointer m: = Man {name: "jack", age: 12} // declare and initialize m: = Man {"jack", 12} // declare and initialize

The method go language defines the structure of a function as a method, which is the same as the object-oriented method. The method definition in the go language looks very avant-garde. The method is the message. Therefore, the method definition first describes the method (Message) receiver, and then the method name and its parameters.
func (m *Man) Introduce() bool {    fmt.Println("name: ",m.name)    return true}

The call method uses the "." symbol:
m := Man{"Jack",12}ok := m.Introduce()
Using the structure method, we can even patch a monkey for the predefined type in the system like ruby to add a new method, but the method is slightly curved, for example, the following code adds a chomp method for the string type to remove the last line break of the string:
Package mainimport ("fmt" "strings") type MyString stringfunc (str MyString) chomp () string {return strings. trimRight (string (str), "\ n")} func main () {str: = "Hello world! \ N "ms: = MyString (str) fmt. Println (ms. chomp () // output Hello world !}


Method proxy google calls this feature Embedded type. If type A contains A type B, we usually call it a has-a B in other languages, but in go, we call a B. This is because B has become A member of A, so we can think that A has B's function, and then it is B. So what is the role of method proxy? As the name suggests, we can directly call the B method on A, just like. b. the same is true for B _method. For example, in matrix, neo is the savior, so it has (including) the capabilities of the Savior. Therefore, we directly send the fly message to neo, neo must be able to fly. Similarly, neo's first generation may not be called neo, But we directly told him that they can fly, so the method proxy is indeed simple:
Package mainimport "fmt" func main () {n: = new (Neo) n. Fly () // output: The One can fly !} Type Neo struct {TheOne} type TheOne struct {} func (o * TheOne) Fly () {fmt. Println ("The One can fly! ")}

In ruby, there are a lot of code for this method proxy, and the expression of the embedded type of the go language is so similar to this feature, we think this embedded type is very similar to the inheritance of OOP. Why is it not called inheritance but method proxy? Actually, Neo only forwards messages to TheOne. Even if the two have the same members, the fly method can only see the member variables of TheOne, so it is more appropriate to call the method proxy, you can write code for verification. Go style duck-type go-style duck type. I personally think this is the most cool part of the go language. In the static language, the duck type of the dynamic language is so cool. The go language interface is born for this purpose. Interface Definition:
type Duck interface {     run()     height() int     gaga(word string)}

The Duck interface only contains a series of method declarations. Then we can use the following in the method parameters:
func DuckRun(d Duck){    d.run()}

So do we need to implement multiple Duck interfaces? NO. That's not the same as java. The only use of the go language interface is actually to satisfy the compiler (alas, somewhat helpless ), in this way, the compiler will check whether the passed object contains the three methods included in the DuckRun function entry. if they conform to the definition, the compiler will compile the method. Isn't that the duck type? Check whether these methods are included, regardless of whether they are of a certain type. Therefore, the duck type of go style is remarkable. For example, a person has a way to say something, but in fact, for a function that requires a say method, we can pass it a earth object, although the Earth does not say anything:
Package mainimport "fmt" func main () {m: = Man {name: "Jack"} m. say () e: = new (Earch) saything (e) saything (& m) // the receiver of the say () method is a pointer variable, so here we need to use & get address} func sayth (obj Object) {obj. say ()} type Object interface {say ()} type Man struct {name string} type Earch struct {} func (m * Man) say () {fmt. println ("Man says: I'm", m. name)} func (e * Earch) say () {// do nothing}

Empty interfaces and empty interfaces (interfaces {}) do not contain any methods. Because of this, all types implement empty interfaces. Empty interfaces do not play any role in the description (because they do not contain any methods), but empty interfaces are useful when we need to store any types of values, because it can store any type of value. It is somewhat similar to the void * type in C language.
// Define a as null interface var a interface {} var I int = 5S: = "Hello world" // a can store any type of value a = I, a = s


If a function uses interface {} as a parameter, it can accept any type of value as a parameter. If a function returns interface {}, it can also return any type of value.
We know that the interface variable can store any type of values (this type implements the interface ). So how do we know the type of objects actually saved in this variable in the reverse direction? You can use Comma-OK to assert
value, ok = element.(T)

Here value is the variable value. OK is a bool type, element is the interface variable, and T is the asserted type.
If the value of the T type is indeed stored in the element, OK returns true; otherwise, false is returned.
In addition, reflection is required when there are more types of processing requirements in the go language. The Go language implements reflection. Reflection is the state of dynamic runtime. We generally use the reflect package. Reflect is generally divided into three steps. The following is a brief explanation: reflection is a type of value (these values implement empty interfaces ), first, you need to convert it into a reflect object (reflect. type or reflect. value ). The two methods are as follows:
T: = reflect. typeOf (I) // obtain the type metadata. With t, we can obtain all the elements in the Type Definition v: = reflect. valueOf (I) // obtain the actual value. Use v to obtain the value stored in it, and change the value.


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.