type Student struct {
m_Addr string
m_ID int
}
func (stu *Student) SetAddr(addr interface{}) (bool, error) {
//这样写法:返回值,bool变量:=interface{}变量.(要判断的具体类型),就是判断是否为指定类型的值。
v, b := addr.(string) //这样就是断言v是string类型的变量,只能赋值给同类型的数值。
if b { //如是上边要判断的string类型,这里会返回true
stu.m_Addr = v
return true, nil
} else { //如不是判断的string类型,会返回false,下面会返回错误信息
return false, fmt.Errorf("不是string类型")
}
}
func (stu *Student) SetStu(data ...interface{}) (bool, error) {
for _, d := range data { //循环遍历参数列表,忽略第一个参数索引
/*这种写法是一个一个类型判断,在判断多个类型时,比较麻烦,使用下面switch case就简便多了
var v, b = d.(string)
if b {
stu.m_Addr = v
}
var v1, b1 = d.(int)
if b1 {
stu.m_ID = v1
}
*/
switch v := d.(type) { //传递type类型,只能在switch case语句使用,返回的v就是具体的值。
case int: //在每一个case判断具体类型,并对返回值v进行处理
stu.m_ID = v
case string:
stu.m_Addr = v
}
}
return true, nil
}