我试过这样做:
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)
}
Run Code Online (Sandbox Code Playgroud)
但我得到了这些错误:
prog.go:30: cannot call pointer method on s.tolower()
prog.go:30: cannot take the address of s.tolower()
Program exited.
Run Code Online (Sandbox Code Playgroud)
为什么我不能让这个链条工作?
Set*_*nig 14
这有效:
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)
}
Run Code Online (Sandbox Code Playgroud)
对于在指向String的指针上定义的函数,返回类型为String.能够将它们链起来是没有意义的.
小智 5
tolower() 和 toupper() 将指向字符串的指针作为接收者,但它们返回字符串(而不是指向字符串的指针)。
您可以通过更改其中之一来解决此问题。
例如,将函数的签名更改为:
func (s *String) toupper() *String
Run Code Online (Sandbox Code Playgroud)
或者
func (s String) toupper() String
Run Code Online (Sandbox Code Playgroud)
(参见: http: //play.golang.org/p/FaCD8AQtIX)