By Ryan Smith


2017-05-02 17:51:53 8 Comments

Using Go's reflect package, is there a way to set a pointer in a struct if the pointer is nil? Looking at the reflect package, if reflect.Value.CanSet() is false then any Set() calls will yield a panic. Is there another way around this, only using the reflect package, not depending on any direct reference to the struct? For example, how can I set the empty last name as "Johnson" in the code below?

package main

import (
    "fmt"
    "reflect"
)

type Person struct {
    FirstName *string
    LastName  *string
}

func main() {
    p := Person{}
    firstName := "Ryan"
    p.FirstName = &firstName

    rp := reflect.ValueOf(p)
    fmt.Println("rp:", rp)

    for i := 0; i < rp.NumField(); i++ {
        fmt.Printf("%s: Pointer: %d CanSet: %t\n", rp.Type().Field(i).Name, rp.Field(i).Pointer(), rp.Field(i).Elem().CanSet())
    }

    rp.Field(0).Elem().SetString("Brian")
    fmt.Println(*p.FirstName)

    // Yields nil pointer error
    // rp.Field(1).Elem().SetString("Johnson")
    // fmt.Println(*p.LastName)

    fmt.Println(rp.Field(1).Type()) 
    fmt.Println(rp.Field(1).CanSet())
    // fmt.Println(rp.Field(1).Elem().Type()) // nil pointer here also
    fmt.Println(rp.Field(1).Elem().CanSet())
}

See in Golang Playground

1 comments

@JimB 2017-05-02 18:06:06

You first need a pointer to a Person{}, because you need to set a value to the LastName Field.

p := &Person{}

Then you can set a valid pointer value to the LastName field, which will allow you to set the string value:

rp.Field(1).Set(reflect.New(rp.Field(1).Type().Elem()))
rp.Field(1).Elem().SetString("Jones")

https://play.golang.org/p/f5MjpkDI2H

Related Questions

Sponsored Content

4 Answered Questions

[SOLVED] Pointers vs. values in parameters and return values

  • 2014-05-08 13:21:41
  • Zef Hemel
  • 72585 View
  • 349 Score
  • 4 Answer
  • Tags:   pointers go

22 Answered Questions

[SOLVED] Get property value from string using reflection

5 Answered Questions

2 Answered Questions

12 Answered Questions

[SOLVED] Setting a property by reflection with a string value

10 Answered Questions

[SOLVED] Set object property using reflection

2 Answered Questions

[SOLVED] Go String after variable declaration

  • 2013-09-08 20:56:43
  • YankeeWhiskey
  • 620 View
  • 3 Score
  • 2 Answer
  • Tags:   syntax go

2 Answered Questions

[SOLVED] Can't set field of a struct that is typed as an interface{}

  • 2018-09-01 01:22:39
  • John
  • 709 View
  • 1 Score
  • 2 Answer
  • Tags:   go go-reflect

1 Answered Questions

Sponsored Content