Go language basic type keyword

 3 minutes to read

go language basic type keyword

The type keyword has the following uses: define structure, define interface, type alias, type definition, type query

1. Define the structure

A structure is a collection of data consisting of a series of data of the same type or different types

type Person struct {
	Name string
	Age int
}
func main() {
	p:=Person{Name: "john",Age:18}
	fmt.Println(p)
}
2. Define the interface

An interface is a collection of unimplemented methods that contain only method names, parameters, and return values.

An interface is considered to be implemented if all methods of the interface are implemented, and no additional declarations are required to appear on the type.

package main

import "fmt"

type Person struct {
	Name string
	Age  int
}

type People interface {
	ReturnName() string
}

func (p Person) ReturnName() string {
	return p.Name
}
func main() {
	p := Person{Name: "john", Age: 18}
	fmt.Println(p)
	fmt.Println(p.ReturnName())

	var a People
	a = p
	name := a.ReturnName()
	fmt.Println(name)

}
3. Type aliases

The type defined using the type alias is the same as the original type, that is, it can be assigned to each other with the original type variable, and it has all the method sets of the original type. Take an alias for the string type, the alias name is name

type name=string

Type aliases differ from type definitions in that using type aliases requires adding an assignment sign (=) between the alias and the original type; A type defined with a type alias is equivalent to the original type, and a type defined with a type is a new type.

package main

import "fmt"

type a=string
type b string

func getValueA(str a)  {
	fmt.Println(str)
}

func getValueB(str b)  {
	fmt.Println(str)
}
func main() {
	var str="Hello"
	getValueA(str)
	getValueB(str)
}

Post-compile prompt cannot use str (type string) as type b in argument to getValueB

4. Type definitions

Type definitions can create new types based on the original type, and in some cases can make the code more concise

package main

import "fmt"

// 将newInt定义为int类型
type newInt int

func main() {
	var a newInt
	a = 100
	fmt.Println(a)        // 100
	fmt.Printf("%T\n", a) // main.newInt
}

define function type

package main

import "fmt"

type handle func(str string)

func exec(f handle)  {
	f("Hello")
}
func main() {
	p:= func(str string) {
		fmt.Println(str,"John")
	}
	exec(p)

	exec(func(str string) {
		fmt.Println(str,"World")
	})
}
5. Type query

Type query is to query the type of the variable according to the variable.

package main

import "fmt"

type Student struct {
	Name string
	Age  int
}

func main() {
	//var a interface{} = Student{Name: "John"}
	var a interface{} = "Hello"
	switch v := a.(type) {
	case string:
		fmt.Println("字符串")
	case int:
		fmt.Println("整型")
	default:
		fmt.Println("其他类型", v)
	}
}