golang编程总结(二)变量声明,重声明,类型断言,类型转换,类型别名
变量声明
func main() {
var name string // [1]
flag.StringVar(&name, "name", "everyone", "The greeting object.") // [2]
// 方式1。
//var name = flag.String("name", "everyone", "The greeting object.")
// 方式2。
//name := flag.String("name", "everyone", "The greeting object.")
flag.Parse()
fmt.Printf("Hello, %v!\n", name)
// 适用于方式1和方式2。
//fmt.Printf("Hello, %v!\n", *name)
}
方式二,只能在函数中使用,自动类型推断,带有一些脚本语言的感觉
重声明
相同类型,名称的变量,嵌套的变量会覆盖被嵌套的变量声明
类型断言
func main() {
container := map[int]string{0: "zero", 1: "one", 2: "two"}
// 方式1。
_, ok1 := interface{}(container).([]string)
_, ok2 := interface{}(container).(map[int]string)
if !(ok1 || ok2) {
fmt.Printf("Error: unsupported container type: %T\n", container)
return
}
fmt.Printf("The element is %q. (container type: %T)\n",
container[1], container)
// 方式2。
elem, err := getElement(container)
if err != nil {
fmt.Printf("Error: %s\n", err)
return
}
fmt.Printf("The element is %q. (container type: %T)\n",
elem, container)
}
func getElement(containerI interface{}) (elem string, err error) {
switch t := containerI.(type) {
case []string:
elem = t[1]
case map[int]string:
elem = t[1]
default:
err = fmt.Errorf("unsupported container type: %T", containerI)
return
}
return
}
类型断言是只能对接口操作的
类型转换
这个没啥好说的,语法和其他语言相通,也可能会丢失数据,比如将一个int64强制转换成int
潜在类型与类型别名
// 示例1。
{
type MyString = string
str := "BCD"
myStr1 := MyString(str)
myStr2 := MyString("A" + str)
fmt.Printf("%T(%q) == %T(%q): %v\n",
str, str, myStr1, myStr1, str == myStr1)
fmt.Printf("%T(%q) > %T(%q): %v\n",
str, str, myStr2, myStr2, str > myStr2)
fmt.Printf( "Type %T is the same as type %T.\n", myStr1, str)
strs := []string{"E", "F", "G"}
myStrs := []MyString(strs)
fmt.Printf("A value of type []MyString: %T(%q)\n",
myStrs, myStrs)
fmt.Printf("Type %T is the same as type %T.\n", myStrs, strs)
fmt.Println()
}
// 示例2。
{
type MyString string
str := "BCD"
myStr1 := MyString(str)
myStr2 := MyString("A" + str)
_ = myStr2
//fmt.Printf("%T(%q) == %T(%q): %v\n",
// str, str, myStr1, myStr1, str == myStr1) // 这里的判等不合法,会引发编译错误。
//fmt.Printf("%T(%q) > %T(%q): %v\n",
// str, str, myStr2, myStr2, str > myStr2) // 这里的比较不合法,会引发编译错误。
fmt.Printf("Type %T is different from type %T.\n", myStr1, str)
strs := []string{"E", "F", "G"}
var myStrs []MyString
//myStrs := []MyString(strs) // 这里的类型转换不合法,会引发编译错误。
//fmt.Printf("A value of type []MyString: %T(%q)\n",
// myStrs, myStrs)
fmt.Printf("Type %T is different from type %T.\n", myStrs, strs)
fmt.Println()
}
// 示例3。
{
type MyString1 = string
type MyString2 string
str := "BCD"
myStr1 := MyString1(str)
myStr2 := MyString2(str)
myStr1 = MyString1(myStr2)
myStr2 = MyString2(myStr1)
myStr1 = str
//myStr2 = str // 这里的赋值不合法,会引发编译错误。
//myStr1 = myStr2 // 这里的赋值不合法,会引发编译错误。
//myStr2 = myStr1 // 这里的赋值不合法,会引发编译错误。
}
type t1 t2表示t2是t1的潜在类型,可以进行强制转换,但不可以直接进行比较
type t1 = t2表示t1,t2是相同的类型,只是名称不同

浙公网安备 33010602011771号