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)
}