当前位置:网站首页>Go language -type keyword

Go language -type keyword

2022-06-21 15:38:00 Crying while learning

type Define simple types

grammar

type keyword   Type name  type
type myint int
type mystring string

func main() {
	var i1 myint = 1
	i2 := 1
	fmt.Printf(" Type comparison :\ti1 The type of :%T\ti2 The type of :%T\n", i1, i2)

	var s1 mystring = "hello"
	s2 := "hello"
	fmt.Printf(" Type comparison :\ts1 The type of :%T\ts2 The type of :%T\n", s1, s2)
}

At this time i1 i2;s1 s2 There are different types of , You can't put i1 i2 or s1 s2 Assign values to each other  .

Type the alias

grammar

type keyword   Type the alias  = type
type myint = int

func main() {
	var i1 myint = 1
	i2 := 1
	fmt.Printf(" Type comparison :\ti1 The type of :%T\ti2 The type of :%T\n", i1, i2)
	fmt.Println(i1 + i2)
}

type Define function types

type myfun func(int, int) string

func fun1() myfun {
	fun := func(a, b int) string {
		s := strconv.Itoa(a) + strconv.Itoa(b)
		return s
	}
	return fun
}

func main() {
	testfun := fun1()
	fmt.Println(testfun(100, 200))
}

原网站

版权声明
本文为[Crying while learning]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206211239019848.html