如何将字符串值转换为函数中的自定义类型
How to convert string value to custom type in function
我写了一个角色检查函数:
...
role = "roles/cloudkms.publicKeyViewer"
func checkRole(key, serviceAccount, role string) bool {
...
return policy.HasRole(serviceAccount, role)
}
然后我收到错误“不能将角色(类型字符串)用作类型”cloud.google。com/go/iam”。policy.HasRole.[=13= 的参数中的 RoleName ]
将角色值转换为自定义类型的正确方法是什么?
// A RoleName is a name representing a collection of permissions.
type RoleName string
// Common role names.
const (
Owner RoleName = "roles/owner"
Editor RoleName = "roles/editor"
Viewer RoleName = "roles/viewer"
)
const (
// AllUsers is a special member that denotes all users, even unauthenticated ones.
AllUsers = "allUsers"
// AllAuthenticatedUsers is a special member that denotes all authenticated users.
AllAuthenticatedUsers = "allAuthenticatedUsers"
)
// HasRole reports whether member has role r.
func (p *Policy) HasRole(member string, r RoleName) bool {
return memberIndex(member, p.binding(r)) >= 0
}
您可以使用如下类型转换:
return policy.HasRole(serviceAccount, iam.RoleName(role))
或者通过将角色声明为 iam.RoleName
来更简单
func checkRole(key, serviceAccount, role iam.RoleName) bool {
...
return policy.HasRole(serviceAccount, role)
}
我写了一个角色检查函数:
...
role = "roles/cloudkms.publicKeyViewer"
func checkRole(key, serviceAccount, role string) bool {
...
return policy.HasRole(serviceAccount, role)
}
然后我收到错误“不能将角色(类型字符串)用作类型”cloud.google。com/go/iam”。policy.HasRole.[=13= 的参数中的 RoleName ]
将角色值转换为自定义类型的正确方法是什么?
// A RoleName is a name representing a collection of permissions.
type RoleName string
// Common role names.
const (
Owner RoleName = "roles/owner"
Editor RoleName = "roles/editor"
Viewer RoleName = "roles/viewer"
)
const (
// AllUsers is a special member that denotes all users, even unauthenticated ones.
AllUsers = "allUsers"
// AllAuthenticatedUsers is a special member that denotes all authenticated users.
AllAuthenticatedUsers = "allAuthenticatedUsers"
)
// HasRole reports whether member has role r.
func (p *Policy) HasRole(member string, r RoleName) bool {
return memberIndex(member, p.binding(r)) >= 0
}
您可以使用如下类型转换:
return policy.HasRole(serviceAccount, iam.RoleName(role))
或者通过将角色声明为 iam.RoleName
func checkRole(key, serviceAccount, role iam.RoleName) bool {
...
return policy.HasRole(serviceAccount, role)
}