Home  >  Article  >  Backend Development  >  What does golang type mean?

What does golang type mean?

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼Original
2019-12-10 10:26:043642browse

What does golang type mean?

type is an important and commonly used keyword in go grammar, and type is by no means just corresponding to typedef in C/C. There are two ways to use type, one is type alias, and the other is type definition. Is it the familiar C language (define and typedef) flavor?

Type definition

type Student struct {
  name String
  age int
}
type I int

Type alias

type Sdt = Student
type I = int

type has the following usages:

Define structure

Define interface

Type definition

Type alias

Type query

Definition Structure

Structure is a user-defined abstract data structure. The struct in golang is similar to the class in the java language. It plays a decisive role in programming. The usage of structures will be introduced in detail in the struct keyword. Let’s take a look at the syntax format for defining a structure:

type name struct {
    Field1  dataType
    Field2  dataType
    Field3  dataType
}

Define the interface

Interface related knowledge points will be introduced in detail in the interface keyword, below Look at the syntax format for defining an interface:

type name interface{
    Read()
    Write()
}

Type definition

The type defined using the type definition is different from the original type, so new type variables cannot be used to assign values ​​to Variables of original type, unless cast is used. Let's take a look at a sample code to define a new type based on the string type. The new type name is name:

type name string

Why use type definition?

Type definition can create a new type based on the original type. In some cases, it can make the code more concise, such as the following sample code:

package main
import (
  "fmt"
)
// 定义一个接收一个字符串类型参数的函数类型
type handle func(str string)
// exec函数,接收handle类型的参数
func exec(f handle) {
  f("hello")
}
func main() {
  // 定义一个函数类型变量,这个函数接收一个字符串类型的参数
  var p = func(str string) {
    fmt.Println("first", str)
  }
  exec(p)
  // 匿名函数作为参数直接传递给exec函数
  exec(func(str string) {
    fmt.Println("second", str)
  })
}

The output information is:

first hello
second hello

The above example is a simple application of type definition. If you do not use type definition, how should you write this code if you want to realize the function in the above example?

// exec函数,接收handle类型的参数
func exec(f func(str string)) {
  f("hello")
}

The parameter type in the exec function needs to be replaced with func (str string). It is not complicated at first glance, but what if exec receives a function variable that requires 5 parameters? Does it feel like the parameter list will be very long?

func exec(f func(str string, str2 string, num int, money float64, flag bool)) {
  f("hello")
}

It can be found from the above code that the readability of the parameter list of the exec function has become worse. Let's take a look at how to implement this function using type definitions:

package main
import (
  "fmt"
)
// 定义一个需要五个参数的函数类型
type handle func(str string, str2 string, num int, money float64, flag bool)
// exec函数,接收handle类型的参数
func exec(f handle) {
  f("hello", "world", 10, 11.23, true)
}
func demo(str string, str2 string, num int, money float64, flag bool) {
  fmt.Println(str, str2, num, money, flag)
}
func main() {
  exec(demo)
}

Type alias

Type alias This feature was introduced in golang1.9. The type defined using a type alias is the same as the original type, that is, it can be assigned to variables of the original type and has all the method sets of the original type. Give the strng type an alias. The alias name is name:

type name = string

The difference between type alias and type definition is that using type alias requires adding an assignment symbol (=) between the alias and the original type; using type The type defined by the alias is equivalent to the original type, while the type defined using the type is a new type.

The following example:

package main
import (
  "fmt"
)
type a = string
type b string
func SayA(str a) {
  fmt.Println(str)
}
func SayB(str b) {
  fmt.Println(str)
}
func main() {
  var str = "test"
  SayA(str)
  
  //错误参数传递,str是字符串类型,不能赋值给b类型变量
  SayB(str)
}

This code will cause the following error when compiling:

.\main.go:21:6: cannot use str (type string) as type b in argument to SayB

It can be seen from the error message that str is a string type and cannot be regarded as b type The parameters are passed into the SayB function. However, str can be passed into the SayA function as a type parameter. It can be seen that the type defined using the type alias is consistent with the original type, while the type defined by the type definition is a new type.

Adding a method to a type alias will be added to the original type method set

After adding a method to a type alias, the original type can also use this method. Please see a sample code below:

package main
import (
  "fmt"
)
// 根据string类型,定义类型S
type S string
func (r *S) Hi() {
  fmt.Println("S hi")
}
// 定义S的类型别名为T
type T = S
func (r *T) Hello() {
  fmt.Println("T hello")
}
// 函数参数接收S类型的指针变量
func exec(obj *S) {
  obj.Hello()
  obj.Hi()
}
func main() {
  t := new(T)
  s := new(S)
  exec(s)
  // 将T类型指针变量传递给S类型指针变量
  exec(t)
}

The output information is:

T hello
S hi
T hello
S hi

In the above example, S is the original type and T is the S type alias. After adding the Hello method to T, variables of type S can also use the Hello method. Note that after adding a method to a type alias, the original type can also use this method. As can be seen from the example, variable t can be assigned to S type variable s, so the type alias is a nickname for the original type, without any change in essence.

Type alias can only affect custom types in the same package. For example, there are many packages in golang sdk. Can we use type aliases to add new methods to the structure types in the sdk package? The answer is: no. Please keep one thing in mind: type aliases can only affect types within the package. If type aliases are used for types outside the package, the following information will be prompted during compilation:

cannot define new methods on non-local type string

Type query

Type query is to query the type of the variable based on the variable. Why is there such a need? There is a special type interface{} in goalng. This type can be assigned to any type of variable. If you want to know which type of variable is assigned to the interface{} type variable, you need to use type query to solve this requirement. The sample code is as follows:

package main
import (
  "fmt"
)
func main() {
    // 定义一个interface{}类型变量,并使用string类型值”abc“初始化
    var a interface{} = "abc"
    
    // 在switch中使用 变量名.(type) 查询变量是由哪个类型数据赋值。
    switch v := a.(type) {
    case string:
      fmt.Println("字符串")
    case int:
        fmt.Println("整型")
    default:
      fmt.Println("其他类型", v)
    }
}

If the variable of type .(type) query is not of interface{} type, the following error will be reported during compilation:

cannot type switch on non-interface value a (type string)

If it is used outside of switch. (type), the following error will be prompted during compilation:

use of .(type) outside type switch

Therefore, when using type for type query, it can only be used in switch, and the variable type used for type query must be interface{}

PHP Chinese website has a large number of free Golang introductory tutorials, everyone is welcome to learn!

The above is the detailed content of What does golang type mean?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn