Golang中如何向User结构体切片添加符合指定JSON格式的新元素
实现方法
你只需要先处理字符串转整型的异常,再用Go内置的切片追加方法即可,结构体已经定义了JSON序列化标签,新添加的元素会自动沿用相同的序列化规则,不需要额外配置。
注意事项
strconv.Atoi() 会返回 (int, error) 两个返回值,不能直接赋值给结构体的Day/Month/Year整型字段,必须先处理转换错误,避免程序panic。
完整示例代码
import "strconv" // 假设以下是你拿到的字符串类型入参 var ( username = "newUser01" password = "mypassword123" confirm_password = "mypassword123" firstname = "Zhang" lastname = "San" dayStr = "12" monthStr = "8" yearStr = "2000" ) // 先执行类型转换,处理错误 day, err := strconv.Atoi(dayStr) if err != nil { // 此处替换为你的业务错误处理逻辑,比如返回参数错误提示 panic("日期参数格式非法") } month, err := strconv.Atoi(monthStr) if err != nil { panic("月份参数格式非法") } year, err := strconv.Atoi(yearStr) if err != nil { panic("年份参数格式非法") } // 构造新User实例,追加到users切片 users = append(users, User{ Username: username, Password: password, ConfirmPassword: confirm_password, Firstname: firstname, Lastname: lastname, Day: day, Month: month, Year: year, })
如果你能100%确定入参的日期字符串是合法整型,不需要做错误校验,可以用忽略错误的写法(不推荐生产环境使用):
day, _ := strconv.Atoi(dayStr) month, _ := strconv.Atoi(monthStr) year, _ := strconv.Atoi(yearStr) users = append(users, User{ Username: username, Password: password, ConfirmPassword: confirm_password, Firstname: firstname, Lastname: lastname, Day: day, Month: month, Year: year, })
内容的提问来源于stack exchange,提问作者Giovanni Mosquera
相关产品推荐
相关产品推荐

