Hi, I’m Mingo.

In their learning Golang this time, I wrote a detailed study notes on my personal number WeChat public Go programming time, for the language, I was a beginner, so writing should fit in with the new to classmates, if you are just learning the language, don’t focus on prevention, study together, Grow together.

My Github:github.com/iswbm/GolangCodingTime my online blog: golang.iswbm.com


Type Assertion

Type Assertion. You can use it to do a few things

  1. checkiWhether it is nil
  2. checkiWhether the value stored is of a certain type

There are two specific ways of use:

The first:

t := i.(T)Copy the code

This expression can assert that an interface object (I) is not nil, and that the interface object (I) stores a value of type T. If the assertion succeeds, the value will be returned to T, and if the assertion fails, panic will occur.

Let’s write some code and try it out

package main import "fmt" func main() { var i interface{} = 10 t1 := i.(int) fmt.Println(t1) FMT. Println (" = = = = = separation line = = = = = ") t2: i. = (string) FMT. Println (t2)}Copy the code

The output is as follows, and you can see that the second assertion failed and panic was triggered

10 ===== partition ===== panic: interface conversion: interface {} is int, not string goroutine 1 [running]: main.main() E:/GoPlayer/src/main.go:12 +0x10e exit status 2Copy the code

If the interface value being asserted is nil, let’s see if panic is triggered as expected

package main

func main() {
    var i interface{} // nil
    var _ = i.(interface{})
}Copy the code

The output is as follows, which does trigger panic

panic: interface conversion: interface is nil, not interface {}

goroutine 1 [running]:
main.main()
        E:/GoPlayer/src/main.go:5 +0x34
exit status 2Copy the code

The second,

t, ok:= i.(T)Copy the code

As above, this expression can also assert that an interface object (I) is not nil, and that the interface object (I) stores a value of type T. If the assertion succeeds, the type is returned to T, and ok is true, indicating success.

If the interface value is of a type other than T, the assertion fails, but unlike the first expression, this does not trigger panic. Instead, it sets ok to false, indicating that the assertion fails, where T is zero for T.

Modify the above example slightly as follows

package main import "fmt" func main() { var i interface{} = 10 t1, ok := i.(int) fmt.Printf("%d-%t\n", t1, Ok) FMT. Println (" = = = = = separation line 1 = = = = = ") t2, ok: i. = (string) FMT. Printf (" % s \ n - % t, "t2, Ok) FMT. Println (" = = = = = = = = = = separation line 2 ") interface var k {} / / nil t3, ok: = k. (interface {}) FMT. Println (t3, "-", Ok) FMT. Println (" = = = = = separation line 3 = = = = = ") k = 10 t4, ok: = k. (interface {}) FMT) Printf (" % d - % t \ n ", t4, ok) t5, ok := k.(int) fmt.Printf("%d-%t\n", t5, ok) }Copy the code

After the run, the output is as follows, and you can see that the second assertion failed but did not trigger panic.

10 - true = = = = = separation line 1 = = = = = = = = = = - false separation line 2 = = = = = < nil > - false = = = = = separation line 3 = = = = = 10-10 - true trueCopy the code

The output of the second assertion before -false does not output any value of t2, but because the assertion failed, t2 gets a string of zero, which is zero length, so you can’t see its output.

Type Switch

If you need to distinguish between multiple types, you can use Type Switch assertions, which are simpler, more direct, and more efficient than type assertions one by one.

package main import "fmt" func findType(i interface{}) { switch x := i.(type) { case int: fmt.Println(x, "is int") case string: fmt.Println(x, "is string") case nil: fmt.Println(x, "is nil") default: fmt.Println(x, "not type matched") } } func main() { findType(10) // int findType("hello") // string var k interface{} // nil FindType findType (k) (10.23) / / float64}Copy the code

The output is as follows

10 is int
hello is string
<nil> is nil
10.23 not type matchedCopy the code

A few extra notes:

  • If your value is nil, then it matchescase nil
  • If your value does not match the corresponding type in switch-case, go to the default branch

Refer to the article

  • Explain Type Assertions in Go
  • Go interface: Type assertion

A series of reading

01. Setup of development environment (Goland & VS Code)

02. Learn five ways to create variables

03. Data type: **Integer and floating point **

Data types: byte, RUNe, and String

05. Data types: Array and slice

06. Data types: dictionary and Boolean

07. Data type: pointer

08. Object-oriented Programming: Structures and Inheritance

09. An article to understand the function in Go

10. Go language flow control: if-else conditional statements

11. Go language flow control: switch-case selection statement

12. Go language flow control: for loop statement

13. Go language flow control: GOto unconditional jump

14. Go language flow control: defer the call

15. Object-oriented programming: Interfaces and polymorphism

Key words: make and new difference?

17. An article to understand the blocks and scopes in Go

18. Learn Go coroutine: Goroutine

19. Learn Go coroutines: Detail channels/channels

20. Several classic error cases of channel deadlock

21. Learn the Go coroutine: WaitGroup

22. Learn Go coroutines: mutex and read-write locks

23. Exception handling in Go: Panic and recover

24. Super detailed interpretation of Go Modules past life and the introduction to use

25. Go language about package import must learn 8 knowledge points

26. How to open source your modules for others to use?

27. What about type assertions in Go?

28. These five points will help you understand the select usage of Go