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

报告相同问题?

悬赏问题

  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?