go: cmd/cgo: compiler accepts invalid declaration of methods on aliases to C types
This program successfully runs with Go 1.21:
$ cat cgo_methods.go
package main
/*
typedef int foo;
*/
import "C"
type foo = C.foo
func (foo) method() int { return 123 }
func main() {
var x foo
println(x.method()) // "123"
}
$ go run cgo_methods.go
123
I believe this program is invalid for the same reason as the program in https://github.com/golang/go/issues/57926. Note that in contrast to that issue, this program uses an alias to define a method on a C type.
About this issue
- Original URL
- State: open
- Created a year ago
- Comments: 15 (9 by maintainers)
Commits related to this issue
- darwin: use Go type wrappers to avoid declaring Go methods on C types. This is needed starting with Go 1.21 due to stricter enforcement of rules about adding methods to existing types, now including ... — committed to deadprogram/go-serial by deadprogram a year ago
- darwin: use Go type wrappers to avoid declaring Go methods on C types. This is needed starting with Go 1.21 due to stricter enforcement of rules about adding methods to existing types, now including ... — committed to deadprogram/go-serial by deadprogram a year ago
@adonovan indeed, I submitted a PR to that repo with fix.
I think this condition is simple to fix this.
fix cl
@alandonovan pointed out this hole in the current cgo detection of methods on C types, and I said it didn’t seem worth worrying about, because who would put a method on a type alias? Interesting to see that people actually do this.
If anybody sees a simple way to fix this, by all means go for it.