duandian8251 2016-07-03 18:48
浏览 107
已采纳

通过反射获取sql.NullString的值

I'd like to get the value of all the fields in a struct that aren't empty. This works for simple primitives (string, int, etc.), but not for struct types such as sql.NullString.

Very simple example:

package main

import (
    "database/sql"
    "fmt"
    "reflect"
)

func main() {
    type fooT struct {
        NullS sql.NullString
    }

    values := reflect.ValueOf(fooT{})

    field := values.Field(0)
    v := reflect.ValueOf(field)

    iface := v.Interface().(sql.NullString)

    fmt.Println(iface)
}

This gives a panic:

panic: interface conversion: interface is reflect.Value, not sql.NullString

I don't understand this, since the Interface method should return an interface{} (and not a reflect.Value) which I can then type assert (?)

First I thought I was maybe using type conversions only works for primitives, but a quick test script:

package main

import (
    "database/sql"
    "fmt"
)

func main() {
    type fooT struct {
        NullS sql.NullString
    }

    foo := fooT{NullS: sql.NullString{"It's an Aardvark!", true}}

    var iface interface{}
    iface = foo.NullS

    fmt.Printf("%T -> %#v
", iface, iface)
    fmt.Printf("%T -> %#v -> %#v
", iface.(sql.NullString), iface.(sql.NullString),
        iface.(sql.NullString).Valid)
}

Reveals that this should work?


The full code I'm using:

package main

import (
    "database/sql"
    "fmt"
    "reflect"
)

type fooT struct {
    ID    int64
    Foo   string
    NullS sql.NullString
    FooQ  sql.NullString
}

func main() {
    foo := fooT{
        ID:    42,
        NullS: sql.NullString{"Your mother was a hamster", true},
    }

    types := reflect.TypeOf(foo)
    values := reflect.ValueOf(foo)

    changed := ""
    for i := 0; i < types.NumField(); i++ {
        fieldType := types.Field(i)
        field := values.Field(i)

        switch field.Type().Kind() {
        // Works
        case reflect.String:
            if field.String() != "" {
                changed += fmt.Sprintf("<strong>%s</strong>: %v<br>
",
                    fieldType.Name, field.String())
            }
        default:
            switch field.Type().String() {
            case "sql.NullString":
                v := reflect.ValueOf(field)

                // NullS: reflect.Value -> sql.NullString{String:"Your mother was a hamster", Valid:true}
                iface := v.Interface()
                fmt.Printf("%s: %T -> %#v
",
                    fieldType.Name, iface, iface)

                // panic: interface conversion: interface is reflect.Value, not sql.NullString
                iface2 := v.Interface().(sql.NullString)
                fmt.Printf("%s: %T -> %#v
",
                    fieldType.Name, iface2, iface2)
            }
        }
    }

    fmt.Printf(changed)
}
  • 写回答

1条回答 默认 最新

  • drxvjnx58751 2016-07-04 07:00
    关注

    I think the problem is that an extra reflect.ValueOf meant that you had a reflect.Value referring to another reflect.Value, not to the NullString. The way Printf formatted it kind of obscured that. It looks like values.Field(i) returns the reflect.Value you need. Here's your program minimally modified by taking out the ValueOf:

    package main
    
    import (
        "database/sql"
        "fmt"
        "reflect"
    )
    
    type fooT struct {
        ID    int64
        Foo   string
        NullS sql.NullString
        FooQ  sql.NullString
    }
    
    func main() {
        foo := fooT{
            ID:    42,
            NullS: sql.NullString{"Your mother was a hamster", true},
        }
    
        types := reflect.TypeOf(foo)
        values := reflect.ValueOf(foo)
    
        changed := ""
        for i := 0; i < types.NumField(); i++ {
            fieldType := types.Field(i)
            field := values.Field(i)
    
            switch field.Type().Kind() {
            // Works
            case reflect.String:
                if field.String() != "" {
                    changed += fmt.Sprintf("<strong>%s</strong>: %v<br>
    ",
                        fieldType.Name, field.String())
                }
            default:
                switch field.Type().String() {
                case "sql.NullString":
            iface := field.Interface()
                    fmt.Printf("%s: %T -> %#v
    ",
                        fieldType.Name, iface, iface)
                }
            }
        }
    
        fmt.Printf(changed)
    }
    

    You may be able to simplify more by using a type switch to do most of the work, like so:

    package main
    
    import (
        "database/sql"
        "fmt"
        "reflect"
    )
    
    type fooT struct {
        ID    int64
        Foo   string
        NullS sql.NullString
        FooQ  sql.NullString
    }
    
    func main() {
        foo := fooT{
            ID:    42,
            NullS: sql.NullString{"Your mother was a hamster", true},
        }
    
        values := reflect.ValueOf(foo)
    
        changed := ""
        for i := 0; i < values.NumField(); i++ {
            v := values.Field(i)
            f := v.Interface()
            switch f := f.(type) {
            case string:
                fmt.Println("string:", f)
            case sql.NullString:
                fmt.Println("NullString:", f.Valid, f.String)
            default:
                fmt.Printf("%s: %v
    ", v.Type(), f)
            }
        }
    
        fmt.Printf(changed)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 ubuntu系统下挂载磁盘上执行./提示权限不够
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型