英文:
Golang append to a slice of type
问题
你可以在每次迭代中使用append
函数将每个用户的参数添加到切片中。以下是一个示例代码:
// 创建一个切片
userslice := make([]keyvalue, 0)
// 迭代每个用户的参数
for _, user := range users {
// 创建一个 keyvalue 对象
kv := make(keyvalue)
// 将用户的参数添加到 keyvalue 对象中
kv["objectClass"] = user.objectClass
kv["cn"] = user.cn
kv["sn"] = user.sn
kv["description"] = user.description
kv["givenName"] = user.givenName
kv["distinguishedName"] = user.distinguishedName
// 将 keyvalue 对象添加到切片中
userslice = append(userslice, kv)
}
在上面的示例中,假设你有一个名为users
的用户列表,每个用户都有相应的参数(如objectClass
、cn
等)。在每次迭代中,我们创建一个keyvalue
对象,并将用户的参数添加到该对象中。然后,我们使用append
函数将该对象添加到userslice
切片中。最终,userslice
将包含所有用户的参数。
英文:
I am doing an ldap query, and I want to populate the result into a slice. The result looks something like
objectClass [top person organizationalPerson user]
cn [user.1]
sn [one]
description [user.1]
givenName [user]
distinguishedName [CN=user.1,OU=random,DC=example,DC=com]
...
I am trying to populate it to a map and for that, I created a type.
type keyvalue map[string]interface{}
Now I want to create a slice of this type, so that the data would look something like this for multiple users taken
objectClass [top person organizationalPerson user]
cn [user.1]
sn [one]
description [user.1]
givenName [user]
distinguishedName [CN=user.1,OU=random,DC=example,DC=com]
...
objectClass [top person organizationalPerson user]
cn [user.2]
sn [one]
description [user.2]
givenName [user]
distinguishedName [CN=user.2,OU=random,DC=example,DC=com]
...
For that, I created a slice of the type that I created above.
userslice := make([]keyvalue, 1, 1)
How will I append each users's parameters into the slice in each iteration?
答案1
得分: 2
只需在代码中使用keyvalue
而不是map[string]interface{}
:
type keyvalue map[string]interface{}
....
user1 := make(keyvalue)
user1["distinguishedName"] = "[CN=user.1,OU=random,DC=example,DC=com]"
user1["givenName"] = "user"
var userslice []keyvalue
userslice = append(userslice, user1)
fmt.Printf("%#v", userslice)
英文:
Just use keyvalue
instead of map[string]interface{}
in your code:
type keyvalue map[string]interface{}
....
user1 := make(keyvalue)
user1["distinguishedName"] = "[CN=user.1,OU=random,DC=example,DC=com]"
user1["givenName"] = "user"
var userslice []keyvalue
userslice = append(userslice, user1)
fmt.Printf("%#v", userslice)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论