< assertions in the Go language >

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

Nonsense

Why do you want to add a sign to the title? Aren't the ideas in programming languages all the same?

Indeed, the basic ideas are the same, and the principles and design philosophies of their respective implementations will differ.

If you have not used the go language before, then it is natural to think that there must be some assert sort of operator or function in the go language. The answer is no, it may disappoint you, you are excitedly looking at an article about the go language, and when you see that there are so few keywords in go, you may be amazed: so concise! But when you formally write code but found: This language is very uncomfortable! No try catch , no generics, no assertions, you must put the starting parenthesis at the end of the statement ...

In fact, you are caught in a misunderstanding, you see the go language from other language perspective, naturally not satisfied with the results.

Problem

I saw this problem in the morning when I was wandering around the StackOverflow:
Http://stackoverflow.com/questions/8103617/call-a-struct-and-its-method-by-name-in-go

I naturally want to map an object in other languages, such as the Python dictionary, the object literal of JS.

So I learned a few days to go to the little Fortune Pen wrote the following test:

 PackageMainImport("FMT"    "Reflect")typeMyStructstruct{}func(A *mystruct) Action () {fmt. Println ("Hello")}funcMain () {varMMap[string]Interface{} M = Make(Map[string]Interface{}, -) m["MyStruct"] = &mystruct{} m: = m["MyStruct"] FMT. Println (reflect. TypeOf (M))//*main. MyStructM.action ()}

The result is a compile error:
m.Action undefined (type interface {} is interface with no methods)

On-line running instance (generally people think that there is no golang.org this website, please resolve the access method by yourself)
https://play.golang.org/p/qnpHmY9S73

I am very strange, reflect.TypeOf obviously detected the type is mystruct, why there is no method?

I overlooked a very obvious problem and didn't go to the official documentation at the same time.
Https://golang.org/ref/spec#Type_assertions

StackOverflow's friends gave me the perfect answer: http://stackoverflow.com/questions/36439733/how-to-referencing-an-object-with-map/ 36439925#36439925

When I declare a map, the declared value is interface{} type, so there is no method for the interface type.

This is an example of an official document:

varinterface{} = 7  // x has dynamic type int and value 7i := x.(int)           // i has type int and value 7

The solution is simple, using the go language to provide the type detection method, but also as an assertion solution:

 PackageMainImport("FMT"    "Reflect")typeMyStructstruct{}func(A *mystruct) Action () {fmt. Println ("Hello")}funcMain () {varMMap[string]Interface{} M = Make(Map[string]Interface{}, -) m["MyStruct"] = &mystruct{} om: = m["MyStruct"]//The type of variable M is interfaceM: = om. (*mystruct)//So asserts this value restored in MFmt. Println (reflect. TypeOf (M))//*main. MyStructM.action ()}

Https://play.golang.org/p/mjxkAeRuDV

m := om.(*MyStruct)

    • If the OM is a mystruct type, the converted type is assigned a value of M.
    • If MyStruct is defined as an interface, this operation succeeds as long as the object that implements the interface is implemented.

It is important to note, however, that if false, that is, a mismatch, a panic error is generated.

There is also a method that does not produce errors.

m, ok := om.(*MyStruct)

The return value is accepted using two variables, and if OK is false, M is zero, but no error is received.

So you can do this for error handling:

if !ok {    fmt.Println("Type not matched!")    os.Exit(1)}

This is actually a simple but criticized value, err := F() design philosophy in Go. Someone joked: When writing a function in other languages, go has already written the function, but when the product written in other languages is already tested, the person with the go language is still writingif err { ... }

Conclusion

English does not improve, do not first go to crossing Web documents, you are a fart.

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.