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

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

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
}

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:

确定