On Fri, 28 Feb 2020 at 08:23, Amnon Baron Cohen <amno...@gmail.com> wrote:
> Here is a dumb version, that wastes loads of memory. > > func reverse(in string) string { > out := strings.Builder{} > out.Grow(len(in)) > runes:= make([]rune, 0, len(in)) > > > for _, r := range in { > runes = append(runes, r) > } > > You might be interested to know that this operation is built in to Go itself, which means you can do something like this: func Reverse(s string) string { runes := []rune(s) rev := make([]rune, 0, len(runes)) for i := len(runes) - 1; i >= 0; i-- { rev = append(rev, runes[i]) } return string(rev) } It's not even *that* much slower (about 60%). It doesn't always preserve the original string length though. On Saturday, 15 February 2020 16:37:15 UTC, Amarjeet Anand wrote: > > Hi > > I was wondering why isn't there built-in string reverse function. Is it > left intentionally because of some reason? > > Although strings are immutable in go, there are multiple ways to achieve > this pretty easily. But having this function inbuilt will save our time > because we need it quite often. > > > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/cae39c11-f492-4890-b0ff-332d2e51042b%40googlegroups.com <https://groups.google.com/d/msgid/golang-nuts/cae39c11-f492-4890-b0ff-332d2e51042b%40googlegroups.com?utm_medium=email&utm_source=footer> . -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CAJhgachKABFxMSqU5xy6hQA_%3DF8gTp9qwTnu6UnhaFYrBSUvnQ%40mail.gmail.com.