dqask02082 2014-01-16 01:38
浏览 497

golang可有效处理Null *类型

If one is working with a database, a Null* type is useful for most scenarios as one typically does not want a "zero" value going through, you want the NOT NULL constraints etc. to kick up and remind you that you haven't passed in all the data necessary.

So you create a structure like the following:

type Role struct {
    Id   sql.NullInt64
    Code sql.NullString
}

Thats great, but now you cannot get direct access to the properties and have to use Role.Id.Value to both get and set, this is going to get pretty old in a large app when you have to have the extra step every single time you want access to the properties.

It would be nice if you could assign directly eg. Role.Code = "Fsfs", and be able to do something like Role.Code.IsNull when you are interested in null checking. Is such a thing possible?

  • 写回答

3条回答 默认 最新

  • doujiang1939 2014-01-16 14:36
    关注

    Is using intermediate pointer value(s) an option?

    package main
    
    import "fmt"
    
    type tmp struct {
        Value int
    }
    
    func getInt() *int {
        i := 123
    
        return &i
    }
    
    func main() {
        // Re
        var v *int
    
        v = nil
    
        fmt.Printf("%T / %v
    ", v, v)
    
        if v == nil {
            println("nil...")
        }
    
        v = getInt()
    
        fmt.Printf("%T / %v
    ", v, *v)
    
        if v != nil {
            println("not nil...")
        }
    
        s := tmp{*v}
    
        fmt.Printf("%T / %v
    ", s, s)
    }
    

    http://play.golang.org/p/lBrwTKh6-v

    评论

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line