github.com/gogf/gf/v2@v2.7.4/container/gvar/gvar_z_unit_struct_test.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/gogf/gf. 6 7 package gvar_test 8 9 import ( 10 "testing" 11 12 "github.com/gogf/gf/v2/container/gvar" 13 "github.com/gogf/gf/v2/frame/g" 14 "github.com/gogf/gf/v2/test/gtest" 15 "github.com/gogf/gf/v2/util/gconv" 16 ) 17 18 func TestVar_Struct(t *testing.T) { 19 gtest.C(t, func(t *gtest.T) { 20 type StTest struct { 21 Test int 22 } 23 24 Kv := make(map[string]int, 1) 25 Kv["Test"] = 100 26 27 testObj := &StTest{} 28 29 objOne := gvar.New(Kv, true) 30 31 objOne.Struct(testObj) 32 33 t.Assert(testObj.Test, Kv["Test"]) 34 }) 35 gtest.C(t, func(t *gtest.T) { 36 type StTest struct { 37 Test int8 38 } 39 o := &StTest{} 40 v := gvar.New(g.Slice{"Test", "-25"}) 41 v.Struct(o) 42 t.Assert(o.Test, -25) 43 }) 44 } 45 46 func TestVar_Var_Attribute_Struct(t *testing.T) { 47 gtest.C(t, func(t *gtest.T) { 48 type User struct { 49 Uid int 50 Name string 51 } 52 user := new(User) 53 err := gconv.Struct( 54 g.Map{ 55 "uid": gvar.New(1), 56 "name": gvar.New("john"), 57 }, user) 58 t.AssertNil(err) 59 t.Assert(user.Uid, 1) 60 t.Assert(user.Name, "john") 61 }) 62 gtest.C(t, func(t *gtest.T) { 63 type User struct { 64 Uid int 65 Name string 66 } 67 var user *User 68 err := gconv.Struct( 69 g.Map{ 70 "uid": gvar.New(1), 71 "name": gvar.New("john"), 72 }, &user) 73 t.AssertNil(err) 74 t.Assert(user.Uid, 1) 75 t.Assert(user.Name, "john") 76 }) 77 }