英文:
Iterate lines through bulk string with go
问题
我有一大段字符串,其中有两列,由空格分隔,第一列是用户名,第二列是密码。我想将该字符串格式化为一个 User
结构体的切片。
字符串的格式如下:
Bob qqweq
Tom erwwe
Andersen sadfadfs
结构体的定义如下:
type User struct{
Username string
Password string
}
在Go语言中,通常如何实现这个功能?
英文:
I have a bulk of string that has two columns split by space, first columns is username and second column is password. I want to format that string to a slice of User
struct
The string is like this:
Bob qqweq
Tom erwwe
Andersen sadfadfs
The struct is simply like this:
type User struct{
Username string
Password string
}
How to do that typically with go?
答案1
得分: 1
这是一种方法:
var users []User
for _, l := range strings.Split(s, "\n") {
f := strings.Fields(l)
if len(f) == 2 {
users = append(users, User{f[0], f[1]})
}
}
<kbd>playground example</kbd>
英文:
Here's one way to do it:
var users []User
for _, l := range strings.Split(s, "\n") {
f := strings.Fields(l)
if len(f) == 2 {
users = append(users, User{f[0], f[1]})
}
}
<kbd>playground example</kbd>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论