Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proposal : Str : string type wrapper to enable python-like string methods chaining : s.ReplaceAll("i", "r").Capitalize() #1322

Closed
serge-hulne opened this issue Jul 5, 2022 · 2 comments

Comments

@serge-hulne
Copy link

serge-hulne commented Jul 5, 2022

Proposal

Aim : provide a type of strings (Str) which enables python-like string methods chaining as in:

s : = Str{"Hello Woild"}
s.ReplaceAll("i", "r").Capitalize()   //-> HELLO WORLD

Background

The motivations are:

  • Emulate the conciseness, expressivity of chaining Python strings.
  • Provide user with a string object which is familiar to Python, JS, TS, C++, Swift, etc. users.

Workarounds

Exemple of implementation:

package str

import "strings"

type Str struct {
	Str string
}

func New(s string) Str {
	return Str{s}
}

func (s Str) String() string {
	return s.Str
}

func (s *Str) Capitalize() *Str {
	s.Str = strings.ToUpper(s.Str)
	return s
}
func (s *Str) ReplaceAll(c1 string, c2 string) *Str {
	s.Str = strings.Replace(s.Str, c1, c2, -1)
	return s
}

Exemple of use:

// Testing Str:
s := Str{"Hello Woild"}
fmt.Printf("%s\n", s.ReplaceAll("i", "r").Capitalize())
println(s.ReplaceAll("i", "r").Capitalize().Str)

Alternative implementation (immutable Str strings):

package str

import "strings"

type Str struct {
	Str string
}

func New(s string) Str {
	return Str{s}
}

func (s Str) String() string {
	return s.Str
}

func (s Str) Capitalize() Str {
	s.Str = strings.ToUpper(s.Str)
	return s
}

func (s Str) ReplaceAll(c1 string, c2 string) Str {
	s.Str = strings.Replace(s.Str, c1, c2, -1)
	return s
}
@serge-hulne serge-hulne changed the title Proposal : Str string type wrapper to enable python-like string methods chaining : s.ReplaceAll("i", "r").Capitalize() Proposal : Str : string type wrapper to enable python-like string methods chaining : s.ReplaceAll("i", "r").Capitalize() Jul 5, 2022
@xushiwei xushiwei added this to the Go+ v1.2 milestone Jul 5, 2022
@xushiwei
Copy link
Member

xushiwei commented Jul 5, 2022

This feature is supported already.

@xushiwei
Copy link
Member

xushiwei commented Jul 5, 2022

s := "Hello world???"
println s.replaceAll("?", "!").toTitle // HELLO WORLD!!!

@xushiwei xushiwei closed this as completed Jul 5, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants