Home > Backend Development > Golang > What is golang assertion?

What is golang assertion?

爱喝马黛茶的安东尼
Release: 2019-12-10 09:37:23
Original
3190 people have browsed it

What is golang assertion?

There is a grammar in the Go language that can directly determine whether it is a variable of this type: value, ok = element.(T), where value is the value of the variable, and ok is a bool Type, element is the interface variable, and T is the asserted type.

If element does store a value of type T, then ok returns true, otherwise it returns false.

package main
 
import (
  "fmt"
)
 
type Order struct {
  ordId   int
  customerId int
  callback func()
}
 
func main() {
  var i interface{}
  i = Order{
    ordId:   456,
    customerId: 56,
  }
  value, ok := i.(Order)
  if !ok {
    fmt.Println("It's not ok for type Order")
    return
  }
  fmt.Println("The value is ", value)
}
Copy after login

Output:

The value is  {456 56 <nil>}
Copy after login

It is also common to use switch to assert:

package main
 
import (
  "fmt"
)
 
type Order struct {
  ordId   int
  customerId int
  callback func()
}
 
func main() {
  var i interface{}
  i = Order{
    ordId:   456,
    customerId: 56,
  }
  switch value := i.(type) {
    case int:
      fmt.Printf("It is an int and its value is %d\n", value)
    case string:
      fmt.Printf("It is a string and its value is %s\n", value)
    case Order:
      fmt.Printf("It is a Order and its value is %v\n", value)
    default:
      fmt.Println("It is of a different type")
    }
}
Copy after login

Output:

It is a Order and its value is {456 56 <nil>}
Copy after login

Golang’s language provides the assertion function. All programs in golang implement the interface{}, which means that all types such as string, int, int64 and even custom struct types have the interface{}. This approach is similar to that in java. The Object type is relatively similar. Then when a piece of data is passed in through func funcName(interface{}), it means that the parameter is automatically converted to the type of interface{}.

For example, the following code:

func funcName(a interface{}) string {
     return string(a)
}
Copy after login

The compiler will return:

cannot convert a (type interface{}) to type string: need type assertion
Copy after login

At this time, it means that the entire conversion process requires type assertion. Type assertions have the following forms:

Direct assertion uses

var a interface{}
fmt.Println("Where are you,Jonny?", a.(string))
Copy after login

, but if the assertion fails, panic will generally occur. So in order to prevent panic from happening, we need to make certain judgments before asserting.

value, ok := a.(string)
Copy after login

If the assertion fails, the value of ok will be false, but if the assertion succeeds, the value of ok will be true, and value will get the correct value expected. Example:

value, ok := a.(string)
if !ok {
    fmt.Println("It&#39;s not ok for type string")
    return
}
fmt.Println("The value is ", value)
Copy after login

In addition, you can also use the switch statement to make judgments:

var t interface{}
t = functionOfSomeType()
switch t := t.(type) {
default:
    fmt.Printf("unexpected type %T", t)       // %T prints whatever type t has
case bool:
    fmt.Printf("boolean %t\n", t)             // t has type bool
case int:
    fmt.Printf("integer %d\n", t)             // t has type int
case *bool:
    fmt.Printf("pointer to boolean %t\n", *t) // t has type *bool
case *int:
    fmt.Printf("pointer to integer %d\n", *t) // t has type *int
}
Copy after login

Also add a few tips for go language programming:

(1) If it does not meet the requirements, you can Return as fast as you can and reduce the use of else statements, which can be more intuitive.

(2) When converting the type, if it is string, there is no need to assert. Use the fmt.Sprint() function to achieve the desired effect.

(3) Variables can be defined and declared in groups, such as:

var (
   a string
   b int
   c int64
   ...
)
import (
    "fmt"
    "strings"
    "net/http"
   ...
)
Copy after login

(4) Function logic is relatively complex, and some logic can be encapsulated into a function to improve readability .

(5) Functions that use the net/http package and the net/url package may have the url encode function, so you need to pay attention.

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 is golang assertion?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template