在Golang中,可以在一行上堆叠多个方法调用。

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

Golang: Stack multiple method calls on one line

问题

开始使用Go语言。
我正在尝试编写一个函数,将名字的第一个字母大写,然后将姓氏全部大写。
为什么我不能像下面这样堆叠方法调用?

(我之所以想在之前加上.ToLower是因为.Title只会将第一个字母大写,而不会改变其他字母)

  1. package main
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. func main() {
  7. firstName := "mElVIn"
  8. lastName := "themelvINATor"
  9. fmt.Println(nameCap(firstName, lastName))
  10. }
  11. func nameCap(s1, s2 string) (str1, str2 string) {
  12. s1 = strings.ToLower(s1).Title(s1)
  13. s2 = strings.ToUpper(s2)
  14. return s1, s2
  15. }
英文:

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)

  1. package main
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. func main() {
  7. firstName := "mElVIn"
  8. lastName := "themelvINATor"
  9. fmt.Println(nameCap(firstName, lastName))
  10. }
  11. func nameCap(s1, s2 string) (str1, str2 string) {
  12. s1 = strings.ToLower(s1).Title(s1)
  13. s2 = strings.ToUpper(s2)
  14. return s1, s2
  15. }

答案1

得分: 2

你可以尝试像这样做(根据你的用例进行修改,我不确定你想要的输出):

  1. type myString string
  2. func main() {
  3. firstName := "mElVIn"
  4. lastName := "themelvINATor"
  5. fmt.Println(nameCap(firstName, lastName))
  6. }
  7. func (s myString) Title(ss string) string {
  8. return strings.Title(ss)
  9. }
  10. func nameCap(s1, s2 string) (str1, str2 string) {
  11. s1 = myString(strings.ToLower(s1)).Title(s1)
  12. s2 = strings.ToUpper(s2)
  13. return s1, s2
  14. }

顺便说一下,不使用链式调用也是可以的:

  1. func nameCap(s1, s2 string) (str1, str2 string) {
  2. s1 = strings.ToLower(s1)
  3. s1 = strings.Title(s1)
  4. s2 = strings.ToUpper(s2)
  5. return s1, s2
  6. }

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):

  1. type myString string
  2. func main() {
  3. firstName := "mElVIn"
  4. lastName := "themelvINATor"
  5. fmt.Println(nameCap(firstName, lastName))
  6. }
  7. func (s myString) Title(ss string) string {
  8. return strings.Title(ss)
  9. }
  10. func nameCap(s1, s2 string) (str1, str2 string) {
  11. s1 = myString(strings.ToLower(s1)).Title(s1)
  12. s2 = strings.ToUpper(s2)
  13. return s1, s2
  14. }

FWIW, there's nothing wrong with doing it without chaining:

  1. func nameCap(s1, s2 string) (str1, str2 string) {
  2. s1 = strings.ToLower(s1)
  3. s1 = strings.Title(s1)
  4. s2 = strings.ToUpper(s2)
  5. return s1, s2
  6. }

GoPlay: http://play.golang.org/p/BcJTuBRqbx

huangapple
  • 本文由 发表于 2016年4月20日 00:36:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/36724389.html
匿名

发表评论

匿名网友

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

确定