Home > Software design >  Set a pointer to an empty interface
Set a pointer to an empty interface

Time:01-09

We are using the openapi-generator to generate a go-gin-server. This generates models containing properties of type *interface{} eg.

type Material struct {
    Id *interface{} `json:"id,omitempty"`
    Reference *interface{} `json:"reference,omitempty"`
}

If I have an instance of this struct, with nil pointers, how can these be set? I have tried the following:

theReturnId := "abc123"
material.Id = &theReturnId

This gives a compilation error of:

cannot use &theReturnId (value of type *string) as *interface{} value in assignment: *string does not implement *interface{} (type interface{} is pointer to interface, not interface)

theReturnId := "abc123"
*material.Id = theReturnId

This gives a runtime error that the pointer is nil.

I have tried a bunch of other things but to no avail. What am I missing here? Thanks!

CodePudding user response:

You almost never need a pointer to an interface. You should be passing interfaces as values, but the underlying data though can still be a pointer.

You need to reconsider your design/code generation technique to not use such an approach as it is not idiomatic Go.


If you still want to use it, use a typed interface{} variable and take its address. The way you are doing in your example is incorrect as theReturnId is a string type taking its address would mean *string type, which cannot be assigned to *interface{} type directly as Go is a strongly typed language

package main

import "fmt"

type Material struct {
    Id        *interface{} `json:"id,omitempty"`
    Reference *interface{} `json:"reference,omitempty"`
}

func main() {
    newMaterial := Material{}
    var foobar interface{} = "foobar"
    newMaterial.Id = &foobar
    fmt.Printf("%T\n", newMaterial.Id)
}
  • Related