Why do []interface{} and interface{} behave differently when they convert the same variable c?

types convert: Why do []interface{} and interface{} behave differently when they convert the same variable c?

What did you do?

In this application, you can see uint8 type c assigning the values to i, i2, and doing the conversion directly, which means you can see he uint8 type c converted to interface{} which is always a consistent address which is understandable here.

And then the second example

This example again uses the type c which uint8 assigns the value to i, In addition, the unsafe package is converted into a pointer p, which is used to modify the value of i. After testing in fmt.Println(c), the value modified by p actually affects C. The output of fmt.Println(c) is 30, but the value of c can be seen through println 20 This is because c is converted into the []interface{} type into fmt.Println and he uint8 is the same memory address when he uint8 does the interface{} conversion

And then the third example

package main

import (
	"fmt"
	"unsafe"
)

type ef struct {
	_type unsafe.Pointer
	data  unsafe.Pointer
}

func main() {
	var c uint32 = 20
	var i interface{} = c
	p := unsafe.Pointer(&i)
	ptr := (*ef)(p)
	p2 := (*int64)(ptr.data)
	*p2 = 30
	println(c)

	fmt.Println(c)

}

Changing c to uint32 et (not uint8 or uint8 type), you can see that modifying the value of p doesn’t affect c, which is for sure because c interprets the address inconsistently incrementing each time through interface{} because golang is a copy of values

Finally, when we add any value to fmt.Println(c), such as fmt.Println(p, c), we find that even the uint32 c variable is changed by p to print 30 in the fourth example

package main

import (
	"fmt"
	"unsafe"
)

type ef struct {
	_type unsafe.Pointer
	data  unsafe.Pointer
}

func main() {
	var c uint32 = 20
	var i interface{} = c
	p := unsafe.Pointer(&i)
	ptr := (*ef)(p)
	p2 := (*int64)(ptr.data)
	*p2 = 30
	println(c)

	fmt.Println(p, c)

}

What did you expect to see?

In the fourth case, when converting c and other params to interface{}, The same memory address is not used. And fmt.Println(c) would be 20 output.

What did you see instead?

I’m confused about the rule of []interface{} doing the transformation, why would this appear the same address when converting uint8 type and others type are not.

Why do []interface{} and interface{} behave differently when they convert the same variable c?

Very grateful for possible answers. and paste the test code below:

package main

import (
	"fmt"
	"unsafe"
)

type ef struct {
	_type unsafe.Pointer
	data  unsafe.Pointer
}

func main() {
	var c uint32 = 20
	var i interface{} = c
	p := unsafe.Pointer(&i)
	ptr := (*ef)(p)
	p2 := (*int64)(ptr.data)
	*p2 = 30
	println(c) // output: 20

	fmt.Println(p, c) // output: 0xc000014270 30
}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.