guregu / null

reasonable handling of nullable values
BSD 2-Clause "Simplified" License
1.84k stars 238 forks source link

Int from string support? #44

Open MikeCongdon1 opened 5 years ago

MikeCongdon1 commented 5 years ago

// NewInt creates a new Int from a string func NewIntFromString(i string, valid bool) Int { if valid { inter, err := strconv.Atoi(i) if err != nil { return Int{ NullInt64: sql.NullInt64{ Int64: 0, Valid: false, }, } } in := int64(inter) return Int{ NullInt64: sql.NullInt64{ Int64: in, Valid: valid, }, } } return Int{ NullInt64: sql.NullInt64{ Int64: 0, Valid: false, }, } } test: func TestNewIntFromString(t testing.T) { type args struct { i string valid bool } tests := []struct { name string args args want Int }{ { name: "equal zero", args: args{ i: "0", valid: false, }, want: IntFrom(0), // TODO: Add test cases. }, { name: "equal one", args: args{ i: "1", valid: true, }, want: IntFrom(1), // TODO: Add test cases. }, } for _, tt := range tests { t.Run(tt.name, func(t testing.T) { if got := NewIntFromString(tt.args.i, tt.args.valid); !reflect.DeepEqual(got, tt.want) { t.Errorf("NewIntFromString() = %v, want %v", got, tt.want) } }) } }

I use this like: id:= zero.NewIntFromString(c.GetQuery("id")) where c is a gin.Context (could do similar with http.GetForm)