Golang cast and type assertion

Time:2022-6-9
catalogue
  • 1. forced type conversion
  • 2. type assertion

1. forced type conversion

Golang is a strongly typed language, but unlike c++ and Java, there is no implicit type conversion in go. The only type conversion in go is forced type conversion and assertion

In Java:

?
1
2
3
4
5
public static void main(String[] args){
    int a = 1;
    double b = 1.0;
    System.out.println(a * b);
}

In Java, this is no problem. The compiler implicitly turns a up todoubletype

However, errors will be reported in go:

Golang cast and type assertion

Cast required:

?
1
2
3
4
5
func Test()  {
 var a int = 1
 var b float32 = 1.0
 fmt.Println(float32(a) * b)
}

Cast in go to:

?
1
type(v)

Common variable typeint,float,string Can be used type (a)In this form,

For example:

?
1
2
3
4
var a int32  = 10
var b int64 = int64(a)
var c float32 = 12.3
var d float64 =float64(c)

Pointer casts requireunsafeFunction implementation in package

?
1
2
3
4
5
6
func Test()  {
 var a int =10
 var b *int =&a
 var c *int64 = (*int64)(unsafe.Pointer(b))
 fmt.Println(*c)
}

2. type assertion

The type judgment in go is to judge whether a variable belongs to a certain type

?
1
2
3
4
5
6
7
func Test()  {
 var a interface{} = 10
 _,isInt := a.(int) // The variable making the type assertion must be an empty interface
 if isInt{
  fmt.Println(a)
 }
}

The form is as follows:

?
1
interface{}.(type)

This is the end of this article about golang forced type conversion and type assertion. For more information about golang type conversion, please search previous articles on developeppaper or continue to browse the following articles. I hope you will support developeppaper in the future!