dtfbj24048 2019-05-29 08:06
浏览 82
已采纳

如何使用反射或其他方式将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.

  • 写回答

1条回答 默认 最新

  • dsz1966 2019-05-29 08:13
    关注

    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,
      }
      
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改