Golang interface interface{}, assertion, switch type

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

interface{} can accept any type of object value
Gets the data type of the interface{} formation, which can be implemented using assertions, or switch type

//Assertion Project Main.go PackageMainImport("FMT")typeBagstruct{Keystring}typeBag2struct{Keyint}funcMain () {varB1Interface{}varB2Interface{} B1 = Bag{key:"1"} b2 = Bag2{key:0}//Get the data type stored in interface{}    //Method One:{//Determine if the bag type is not set to 0B, OK: = B1. (Bag) fmt. Println ("bag type:"Ok"Data", b)} {//Determine if the Bag2 type is not set to 0B, OK: = B2. (BAG2) fmt. Println ("Bag2 type:"Ok"Data", b)}//Method two:    SwitchV: = B1. (type) {//v represents the value of the B1 interface converted to a Bag object     CaseBag:fmt. Println ("B1. (type): ","Bag", V) CaseBag2:fmt. Println ("B1. (type): ","Bag2", V)default: FMT. Println ("B1. (type): ","Other", V)}}

Assertion: A data type that is typically used for objects in known interface, which automatically converts an interface to the appropriate object, a syntax structure interface object (obj), a data type (string), V,ok: = obj. (string), if the corresponding object OK is true, V is the corresponding object and data.

Switch type: a known or unknown object data type is available, B1. (type) must be used with switch to execute this statement alone.
Switch v:= B1. (type) {//B1 is a interface object and V is the corresponding object and data
Case Bag://Type is bag when executed
Fmt. Println ("B1." ( Type): "," Bag ", V)
Case bag2://type is Bag2 when executed
Fmt. Println ("B1." ( Type): "," Bag2 ", V)
default://is executed when the type is another type
Fmt. Println ("B1." ( Type): "," other ", V)
}

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.