Type assertions in the Go language

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed. [] (https://raw.githubusercontent.com/studygolang/gctt-images/master/type-assertion/1_ P6c6i0nihnoilrbsahd3la.jpeg) <center>[https://en.wikipedia.org/wikipsycho_ (1960_film)] (https:// En.wikipedia.org/wiki/psycho_%281960_film%29) </center> type assertion is used to check whether the value held by the interface type variable implements the desired interface or specific type. The syntax for type assertion is defined as follows: "' Goprimaryexpression. The (Type) ' primaryexpression can be found in the [Go Language Specification] (HTTPS://GOLANG.ORG/REF/SPEC#PRIMARYEXPR), and it can be an identifier, an array element of a particular index, a slice, and so on. Type can be either a type identifier or a type literal, such as: ' ' Gotype I Interface {walk () quack ()}type S Struct{}func (S S) walk () {}func (s) quack () {}v Ar i Ii = s{}fmt. Println (I. (Interface {walk ()})) ' Primaryexpression must be an interface type, otherwise a compile-time error will occur: ' ' Gotype I Interface{walk () quack ()}type S struct{}s{}. (I)//Invalid type assertion: s{}. (I) (S is not an interface type on the left side of the operator) ' > If the expression is nil, the type assertion will not be true. # # Dynamic Type variables in addition to static types (types in variable declarations), interface variables also have dynamic types. Is the value of a type set in the current interface type variable. In the process of program execution, the variables of the interface type have the same static type, but their dynamic type will vary with the interface it implements, and its value will change as well. "' Gotype I Interface {walk ()}type A Struct{}func (a A) walk () {}type B struct{}func (b b)The dynamic type of walk () {}func main () {var i Ii = a{}//I is afmt.printf ("%t\n", I. (A)) i = b{}//I is a dynamic type of bfmt.printf ("%t\n", I (B))} The "# # interface type if T from V. (t) is an interface type, such an assertion check that can be used to detect whether V's dynamic type implements the interface T: ' ' Gotype I interfacce {walk ()}type J Interface {quack ()}t Ype K Interface {bark ()}type S Struc{}func (S S) walk () {}func (s) quack () {}func main () {var i Ii = s{}fmt. Printf ("%t\n", I. (J)) fmt. Printf ("%t\n", I. (K))//Panic: interface conversion: Main. S is not main. K: Missing Method Bark} ' # # non-interface type if T from V. (t) is not an interface type, so the assertion checks if the dynamic type V is the same as the T type: ' ' Gotype I Interface {walk ()}type a struct{}func (A A) walk () {}type B struct{}func (b b) walk () {}func main () {var i Ii = a{}fmt. Printf ("%t\n", I. (A)) fmt. Printf ("%t\n", I. (B))//Panic: interface conversion: Main. I is main. A, not main. B} "in the case of a non-interface type to pass the type must implement the interface I, if not meet this requirement will be captured at compile time:" ' Gotype C struct{}fmt. Prinf ("%t\n", I. (C)) "Output:> Impossible Type assertion: > C does not implement I (Missing Walk method) # # Do not panic in the above situation The runtime panic will be triggered when the assertion cannot be established. In order to gracefully handle errors, there are special forms to assign or initialize: "' Gotype I interface {Walk ()}type A struct {name String}func (a A) walk () {}type b struct {name String}func (b b) walk () {}func main () {var i Ii = a{ Name: "foo"}vala, OkA: = i. (A) fmt. Printf ("% #v% #v \ n", ValA, OkA) valb, OkB: = I. (B) FMT. Printf ("% #v% #v \ n", Valb, OkB)} "output:" ' Bashmain. A{name: "foo"} truemain. B{name: ""} false "> when the assertion is not true, the first value will be the [0 value] of the test type (https://golang.org/ref/spec#The_zero_value) # resource: * [GO programming language Specification-Go Programming language] (https://golang.org/ref/spec#TypeAssertion) * [Go is a common language that is designed with system programming in mind. It is strongly typed and has a garbage collection mechanism ...] (https://golang.org/ref/spec#TypeAssertion) * [golang.org] (https://golang.org/ref/spec#TypeAssertion)

Via:https://medium.com/golangspec/type-assertions-in-go-e609759c42e1

Author: Michałłowicki Translator: fredvence proofreading: Rxcai

This article by GCTT original compilation, go language Chinese network honor launches

This article was originally translated by GCTT and the Go Language Chinese network. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Gctt!
Translation work and translations are published only for the purpose of learning and communication, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work has violated your interests, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translation link and author/translator information in the text.
The article only represents the author's knowledge and views, if there are different points of view, please line up downstairs to spit groove

342 Reads
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.