This is a creation in Article, where the information may have evolved or changed.
The syntax for the COMMA-OK assertion is: value, OK: = element. (T). element must be a variable of the interface type, and T is a normal type. If the assertion fails, OK is false, otherwise OK is true and value is the values of the variable. Let's look at an example:
Package Mainimport ("FMT") type HTML []interface{}func main () {html: = make (HTML,5) html[0] ="Div"html[1] ="Span"html[2] = []byte("Script") html[3] ="Style"html[4] ="Head" forIndexelement: = Range HTML {if value, OK: =element. (string); OK {fmt. Printf ("html[%d] is a string and its value is%s\n", Index,value) }Else if value, OK: =element. ([]byte); OK {fmt. Printf ("html[%d] is a []byte and its value is%s\n", Index,string(value)) } }}
In fact, the COMMA-OK assertion also supports another way to simplify usage: value: = element. (T). But this approach is not recommended because once element is used. (T) assertion fails, a run-time error is generated. Such as:
package mainimport ( "fmt")func main() { varinterface"good" fmt.Println(val.(string)) // fmt.Println(val.(int))}
The line that is commented on in the above code will run as an error. This is because Val is actually storing a string type, so the assertion fails.
Another way to convert is the switch test. Since this is called a switch test, this conversion method can only appear in the switch statement. It is easy to replace the example with the COMMA-OK assertion with the switch test to achieve:
PackageMainImport("FMT")typeHtml []Interface{}funcMain () {html: = Make(Html,5) HTML[0] ="Div"Html[1] ="Span"Html[2] = []byte("Script") HTML[3] ="Style"Html[4] ="Head" forIndex, element: =RangeHTML {SwitchValue: = element. (type) { Case string: FMT. Printf ("html[%d] is a string and its value is%s\n", index, value) Case[]byte: FMT. Printf ("html[%d] is a []byte and its value is%s\n", Index,string(value)) Case int: FMT. Printf ("Invalid type\n")default: FMT. Printf ("Unknown type\n") } }}