Home > Blockchain >  Conversion among struct types with unexported fields
Conversion among struct types with unexported fields

Time:10-20

From the specs on conversion, I read

A non-constant value x can be converted to type T in any of these cases:

  • [..]
  • ignoring struct tags (see below), x's type and T are not type parameters but have identical underlying types.
  • [..]

From the above specs, I would have expected the following code to compile

package main

import "github.com/fxtlabs/date"

type Date struct {
    day int32
}

func main() {
    _ = date.Date(Date{12345})
}

However, it does not compile with error message

cannot convert Date{…} (value of type Date) to type date.Date

Note that "github.com/fxtlabs/date".Date is defined here as

type Date struct {
    // day gives the number of days elapsed since date zero.
    day int32
}

Why does it fail to compile? Is it because the field day from "github.com/fxtlabs/date".Date is unexported? If yes, shouldn't this be specified in the specs?

CodePudding user response:

Is it because the field day from "github.com/fxtlabs/date".Date is unexported?

Yes.

If yes, shouldn't this be specified in the specs?

It is in the spec under Type Identity.

Two struct types are identical if they have the same sequence of fields, and if corresponding fields have the same names, and identical types, and identical tags. Non-exported field names from different packages are always different.

In other words, the underlying types are NOT identical because their fields are unexported.

Example of identical types struct {Day int32} (packag a) and struct{Day int32} (package b). Example of NOT identical types struct {day int32} (packag a) and struct{day int32} (package b).

  • Related