Golang追加到指定类型的切片

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

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的用户列表,每个用户都有相应的参数(如objectClasscn等)。在每次迭代中,我们创建一个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)

huangapple
  • 本文由 发表于 2016年2月15日 13:31:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/35402105.html
匿名

发表评论

匿名网友

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

确定