Why is this rule for composite types?

From Go Faq.

In Go, types are closely tied to methods, in that every named type has a (possibly empty) method set. The general rule is that you can change the name of the type being converted (and thus possibly change its method set) but you can’t change the name (and method set) of elements of a composite type. Go requires you to be explicit about type conversions.

What difference does it make with explicit conversion on single vs composite element.

type T1 int
type T2 int
var t1 T1
var x = T2(t1) // OK
var st1 []T1
var sx = ([]T2)(st1) // NOT OK
1 Like

Just for the sake of Programmers’ awareness?

The “single element” was explicitly converted.

Was slipped a bit, I edited my question… crux is, in both the cases we are explicit so why composite wants us to be super-explicit?

“A slice is a descriptor of an array segment. It consists of a pointer to the array segment, the length of the segment, and its capacity” (https://blog.golang.org/slices-intro). The slice descriptor does not have any type information so how could it know how to cast the slice members to another type?

Perhaps there’s something in the go generics implementation that will help you.

The slice descriptor does not have any type information so how could it know how to cast the slice members to another type?

Obviously, it is the job of the compiler, compiler knows the type information and what type casts are legal – given here ([]T2)(st1) the underlying types are same… Even according to your logic var x = T2(t1) // OK T2 is int, do you think a type (int) has an intelligence to weigh in on type-casting? it is the compiler’s job.

I think the relevant part of the spec is the paragraph on non-constant conversions, but I can’t tell exactly why this isn’t allowed.

Maybe because people wouldn’t get why it doesn’t work with slices of different underlying types (e.g. "why can I say var f *os.File; var r io.Reader = (io.Reader)(f), but not var fs []*io.File; var rs []io.Reader = ([]io.Reader)(fs)?”).

It’s an interesting question!

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