create Golang project with interface #2

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]

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值