如何使用反射或其他方式将interface {}转换为sql.NullString

I have created a map[string]interface{}, and populated it as such.

sli := make(map[string]interface{})

    str := new(sql.NullString)

    str.String = "hello"
    str.Valid = true

    i64 := new(sql.NullInt64)

    i64.Int64 = 55
    i64.Valid = true

    sli["first"] = str
    sli["second"] = i64

This all populates fine but when I try and accessthe string from the sql.NullString element in the map I get a panic.

interface conversion: interface {} is *sql.NullString, not sql.NullString

Here is the code I am using to access the string...

temp := sli["first"]
    temptype := reflect.TypeOf(temp).String()
    if temptype == "*sql.NullString" {
        s := sql.NullString{}
        s = temp.(sql.NullString)
        s2 := s.String
        fmt.Print(s2)
    }

I have tried change the type to sql.Nullstring as the error suggested but it does not then see the if condition as true.

new() creates a nil pointer to the type requested. So it's expected that you're creating a *sql.NullString rather than a sql.NullString. Your options are:

  1. Convert it correctly for the type:

    s = temp.(*sql.NullString)
    
  2. Don't create a pointer:

    str := sql.NullString{}
    
    str.String = "hello"
    str.Valid = true
    

    which can be shortened to:

    str := sql.NullString{
        String: "hello",
        Valid:  true,
    }