从博客《Golang 数组、切片和字符串》中:

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

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 &#39;a&#39; &lt;= b &amp;&amp; b &lt;= &#39;z&#39; {
            (*p)[i] = b + &#39;A&#39; - &#39;a&#39; // derefernce p here as well
        }
    }
}

Working code: https://play.golang.org/p/feqeAlb80z

huangapple
  • 本文由 发表于 2016年9月26日 18:39:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/39700671.html
匿名

发表评论

匿名网友

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

确定