英文:
From blog golang arrays slices and strings
问题
类型 path 是一个字节切片。
将 ToUpper 方法转换为指针接收器的方法,看看它的行为是否会改变。
如何使用指针方法?我尝试过对 *p 进行解引用,还尝试删除 range 中的 i,但它一直显示类型不匹配。
英文:
type path []byte
func (p path) ToUpper() {
for i, b := range p {
if 'a' <= b && b <= 'z' {
p[i] = b + 'A' - 'a'
}
}
}
func main() {
pathName := path("/usr/bin/tso")
pathName.ToUpper()
fmt.Printf("%s\n", pathName)
}
[Exercise: Convert the ToUpper method to use a pointer receiver and see if its behavior changes.]
how to use a pointer method ? i have tried to dereference *p and tried to delete i from range but it keeps saying mismatched types.
答案1
得分: 1
由于path
是在[]byte
上定义的类型,而[]byte
恰好是一个切片,所以不需要使用指针接收器,因为切片类型已经是引用类型。
然而,如果需要使用指针接收器,你需要在方法的每个地方解引用指针值,以获取底层的切片值:
func (p *path) ToUpper() {
for i, b := range *p { // 使用 * 解引用 p,获取底层的 []byte 切片
if 'a' <= b && b <= 'z' {
(*p)[i] = b + 'A' - 'a' // 这里也需要解引用 p
}
}
}
工作代码:https://play.golang.org/p/feqeAlb80z
英文:
Since path
is a type defined on a []byte
which happens to be a slice, there is no need to use a pointer receiver since slice types are already reference types.
However, if a pointer receiver is required, you'll need to dereference the pointer value everywhere in your method to get the underlying slice value:
func (p *path) ToUpper() {
for i, b := range *p { // dereference p with a * to get the
// underlying []byte slice
if 'a' <= b && b <= 'z' {
(*p)[i] = b + 'A' - 'a' // derefernce p here as well
}
}
}
Working code: https://play.golang.org/p/feqeAlb80z
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论