type User struct { Name string }
func test(o interface{}) {
t := reflect.TypeOf(o)
fmt.Println(t)
}
u := &User{"Bob"}
test(u.Name) // prints "string", but I need "Name"
Is this possible in Go? I want to have as few "magic strings" as possible, so instead of having
UpdateFields("Name", "Password")
I'd much rather use
UpdateFields(user.Name, user.Password)
You can't do that. The closest thing I can think of, but it's damn ugly so do not take it as the answer is something like this:
package main
import(
"fmt"
"reflect"
)
type Foo struct {
Bar string
Baz int
}
var Foo_Bar = reflect.TypeOf(Foo{}).Field(0).Name
var Foo_Baz = reflect.TypeOf(Foo{}).Field(1).Name
func main(){
fmt.Println(Foo_Bar, Foo_Baz)
}
You can make this work by defining a new type that is based off of string, and use that as the type inside of your struct:
package main
import "fmt"
import "reflect"
type Name string
type User struct {
Name Name
}
func test(o interface{}) {
t := reflect.TypeOf(o)
fmt.Println(t.Name())
}
func main() {
u := &User{"Bob"}
test(u.Name) // Prints "Name"
test("Tim") // Prints "string"
}