Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

reflect.SliceHeader expects incorrect field types #3372

Closed
bjatkin opened this issue Jan 7, 2023 · 2 comments
Closed

reflect.SliceHeader expects incorrect field types #3372

bjatkin opened this issue Jan 7, 2023 · 2 comments
Labels
reflection Needs further work on reflection

Comments

@bjatkin
Copy link

bjatkin commented Jan 7, 2023

The following code does not compile correctly when using the tinygo compiler

package main

import (
	"fmt"
	"reflect"
	"unsafe"
)

func main() {
	a := []int{0, 1, 2, 3, 4}
	b := reflect.SliceHeader{
		Data: uintptr(unsafe.Pointer(&a[0])),

		Len: len(a),
		Cap: len(a),
	}

	fmt.Println(b)
}

when running tinygo run . I get the following output

main.go:14:8: cannot use len(a) (value of type int) as uintptr value in struct literal
main.go:15:8: cannot use len(a) (value of type int) as uintptr value in struct literal

surprisingly however, when I change the types of the Len and Cap fields to uintptrs, the code complies successfully and runs correctly.

func main() {
	a := []int{0, 1, 2, 3, 4}
	b := reflect.SliceHeader{
		Data: uintptr(unsafe.Pointer(&a[0])),

		Len: uintptr(len(a)),
		Cap: uintptr(len(a)),
	}

	fmt.Println(b)
}

This new code however, will not compile when using the go compiler as the SliceHeader type expects ints for it's length and capacity.

runninggo run . with this version of the code results in the following error

./main.go:14:8: cannot use uintptr(len(a)) (value of type uintptr) as type int in struct literal
./main.go:15:8: cannot use uintptr(len(a)) (value of type uintptr) as type int in struct literal

I believe the behavior of the go compiler is correct here and the tinygo compiler should be updated to expect int values for the Len and Cap fields in the reflect.SliceHeader type.

I'm using tinygo version 0.26.0

tinygo version 0.26.0 linux/amd64 (using go version go1.19 and LLVM version 14.0.0)
@dgryski
Copy link
Member

dgryski commented Jan 7, 2023

Yes. Please see #1284 .

@deadprogram deadprogram added the reflection Needs further work on reflection label Jan 8, 2023
@bjatkin
Copy link
Author

bjatkin commented Jan 11, 2023

I appreciate the context. I will port my code to instead use the new unsafe.Slice() function introduced in 1.17

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
reflection Needs further work on reflection
Projects
None yet
Development

No branches or pull requests

3 participants