gpt4 book ai didi

go - Go中的链接函数?

转载 作者:IT老高 更新时间:2023-10-28 13:09:49 27 4
gpt4 key购买 nike

我试过这样做:

package main

import (
"fmt"
"strings"
)

type String string


func (s *String) tolower() String {
*s = String(strings.ToLower(string(*s)))
return *s
}

func (s *String) toupper() String {
*s = String(strings.ToUpper(string(*s)))
return *s
}

func main() {
var s String = "ASDF"
(s.tolower()).toupper() // this fails
// s.toupper();s.tolower(); // this works
// s.tolower().toupper() // this fails too
fmt.Println(s)
}

但我收到了这些错误:

prog.go:30: cannot call pointer method on s.tolower()
prog.go:30: cannot take the address of s.tolower()

Program exited.

为什么我不能让这条链工作?

最佳答案

这行得通:

package main

import (
"fmt"
"strings"
)

type String string


func (s *String) tolower() *String {
*s = String(strings.ToLower(string(*s)))
return s
}

func (s *String) toupper() *String {
*s = String(strings.ToUpper(string(*s)))
return s
}

func main() {
var s String = "ASDF"
(s.tolower()).toupper()
s.toupper();
s.tolower();
s.tolower().toupper()
fmt.Println(s)
}

您的返回类型是字符串,用于在指向字符串的指针上定义的函数。能够将它们链接起来是没有意义的。

关于go - Go中的链接函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18152419/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com