Go's Reflect Package is Mostly Read-Only
Today, after playing with the reflect
package I discovered that you can’t use it as
a construction kit.
For reasons that I hope to get into another time, I was trying to create
reflect
values by hand today. Imagine that you have this struct type:
type Person struct {
Name string
Born time.Time
}
My intention was, without the code above, to create the same value I would have gotten back if I’d done something like:
var p Person
personType := reflect.TypeOf(p)
Here’s what I ended up with:
fields := []reflect.StructField{{
Name: "Name",
Type: reflect.TypeOf(string("")),
}, {
Name: "Born",
Type: reflect.TypeOf(time.Now()),
}}
personType := reflect.StructOf(fields)
Sadly, that’s insufficient. The second example above is an anonymous struct
of Name string, Born time.Time
. It would work in many cases, but not all.
Fundamentaly, from a user’s perpective, the distinction is that the first
example has a name (Person) and that the latter is anonymous.
The ultimate implication here is that, while reflect
can be used for inputs to
packages (even though it generally shouldn’t) you can’t use it as a general
interface. You just can create reflect
values of types that you don’t have in
your running process.
(The following includes affiliate links.)
If you are interested in learning Go, this is my recommendation:
If you don’t already know Go, you should definitely check out The Go Programming Language. It’s not just a great Go book but a great programming book in general with a generous dollop of concurrency.
Another book to consider learning Go with is Go Programming Blueprints. It has a nearly interactive style where you write code, see it get syntax errors (or whatever,) fix it, and iterate. A useful book that shows that you don’t have to get all of your programs perfectly working on the first compile.
Posted Thu, Oct 17, 2019If you're interested in being notified when new posts are published, you can subscribe here; you'll get an email once a week at the most.