英文:
Golang: Stack multiple method calls on one line
问题
开始使用Go语言。
我正在尝试编写一个函数,将名字的第一个字母大写,然后将姓氏全部大写。
为什么我不能像下面这样堆叠方法调用?
(我之所以想在之前加上.ToLower是因为.Title只会将第一个字母大写,而不会改变其他字母)
package main
import (
"fmt"
"strings"
)
func main() {
firstName := "mElVIn"
lastName := "themelvINATor"
fmt.Println(nameCap(firstName, lastName))
}
func nameCap(s1, s2 string) (str1, str2 string) {
s1 = strings.ToLower(s1).Title(s1)
s2 = strings.ToUpper(s2)
return s1, s2
}
英文:
Getting started with Go.
I'm trying to write a function that title cases a first name then caps the second.
Why can't I stack method calls as below?
(The reason why I want to put a .ToLower before is because the .Title only caps the first letter leaving the rest unchanged)
package main
import (
"fmt"
"strings"
)
func main() {
firstName := "mElVIn"
lastName := "themelvINATor"
fmt.Println(nameCap(firstName, lastName))
}
func nameCap(s1, s2 string) (str1, str2 string) {
s1 = strings.ToLower(s1).Title(s1)
s2 = strings.ToUpper(s2)
return s1, s2
}
答案1
得分: 2
你可以尝试像这样做(根据你的用例进行修改,我不确定你想要的输出):
type myString string
func main() {
firstName := "mElVIn"
lastName := "themelvINATor"
fmt.Println(nameCap(firstName, lastName))
}
func (s myString) Title(ss string) string {
return strings.Title(ss)
}
func nameCap(s1, s2 string) (str1, str2 string) {
s1 = myString(strings.ToLower(s1)).Title(s1)
s2 = strings.ToUpper(s2)
return s1, s2
}
顺便说一下,不使用链式调用也是可以的:
func nameCap(s1, s2 string) (str1, str2 string) {
s1 = strings.ToLower(s1)
s1 = strings.Title(s1)
s2 = strings.ToUpper(s2)
return s1, s2
}
GoPlay链接:http://play.golang.org/p/BcJTuBRqbx
英文:
You could try to do something like this (modify for your use case, I'm not entirely sure the output you're trying to get):
type myString string
func main() {
firstName := "mElVIn"
lastName := "themelvINATor"
fmt.Println(nameCap(firstName, lastName))
}
func (s myString) Title(ss string) string {
return strings.Title(ss)
}
func nameCap(s1, s2 string) (str1, str2 string) {
s1 = myString(strings.ToLower(s1)).Title(s1)
s2 = strings.ToUpper(s2)
return s1, s2
}
FWIW, there's nothing wrong with doing it without chaining:
func nameCap(s1, s2 string) (str1, str2 string) {
s1 = strings.ToLower(s1)
s1 = strings.Title(s1)
s2 = strings.ToUpper(s2)
return s1, s2
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论