1, create new project "test10_assert"
$ cd ~/project
$ mkdir test10_assert
$ cd test10_assert
$ touch assert.go
2,add following lines in “assert.go”
package main
import (
"fmt"
)
type Mint int
type Name struct {
firstName string
secondName string
}
type Addr [4]byte
type example interface {}
func main() {
// TEST 1, assert parameter type if we are not sure about it
var num Mint = 123
var name = Name{"11", "22"}
fmt.Printf("%T, %T\n", num, name)
var exp example
exp = num // exp = name
if value, ok := exp.(Mint); ok {
fmt.Println("parameter num is in type Mint:", value)
} else {
fmt.Printf("parameter num is not in type Mint but %T\n", exp)
}
exp = name // exp = num
if value, ok := exp.(Name); ok {
fmt.Println("find a parameter with type Name:", value)
} else {
fmt.Printf("parameter name is not in type Name but %T\n", exp)
}
// TEST 2, assume a parameter type is not clear, maybe one of [int, float64, string, Mint, Name]
var param float32 = 9.9
exp = param // 12, 33.44, "hello", num, name
switch _type := exp.(type) {
case int:
fmt.Println("case 1 --- int")
case float64:
fmt.Println("case 2 --- float64")
case string:
fmt.Println("case 3 --- string")
case Mint:
fmt.Println("case 4 --- Mint")
case Name:
fmt.Println("case 5 --- Name")
default:
fmt.Printf("default --- %T, %v\n", _type, _type)
}
// TEST 3, implement interface String in struct Name
fmt.Println(name)
// TEST 4, implement interface String in []byte
var IP = make(map[string]Addr)
IP["host"] = Addr{127, 0, 0, 1}
IP["port"] = Addr{0, 0, 0, 8}
fmt.Println(IP)
}
func (n Name) String() string {
return fmt.Sprintf("[first_name: %v, second_name: %v]", n.firstName, n.secondName)
}
func (add Addr) String() string {
var res string
for idx, v := range add {
res += fmt.Sprintf("%v", v)
if idx < (len(add)-1) {
res += "."
}
}
return res
}
3, run “assert.go”
go run assert.go
you should get result like this:
main.Mint, main.Name
parameter num is in type Mint: 123
find a parameter with type Name: [first_name: 11, second_name: 22]
default --- float32, 9.9
[first_name: 11, second_name: 22]
map[host:127.0.0.1 port:0.0.0.8]