使用Go迭代遍历批量字符串的行。

huangapple go评论86阅读模式
英文:

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, &quot;\n&quot;) {
	f := strings.Fields(l)
	if len(f) == 2 {
		users = append(users, User{f[0], f[1]})
	}
}

<kbd>playground example</kbd>

huangapple
  • 本文由 发表于 2015年3月14日 13:13:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/29045707.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定