Go Map()

regantewksbury's avatar
Published Sep 28, 2023
Contribute to Docs

The strings.Map() method changes the characters of a provided string according to a given mapping function. It returns a modified copy of the original string.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn how to use Go (Golang), an open-source programming language supported by Google!
    • Beginner Friendly.
      6 hours

Syntax

strings.Map(mappingFunc(r), s)

The strings.Map() function takes two parameters:

  • mappingFunc(r): A function and a character (type rune) that the original character will be replaced with.
  • s: The given string in which the characters will be replaced.

Note: If a negative value is returned when a character is mapped, it is dropped from the string without a replacement.

Example

The following example shows the implementation of strings.Map():

package main
import (
"fmt"
"strings"
)
func main() {
mapped := func(r rune) rune {
if r == 'e' {
return '3'
}
return r
}
input := "Halloween"
result := strings.Map(mapped, input)
fmt.Println(result)
}

This example results in the following output:

Hallow33n

Codebyte Example

The following example can be run and uses the strings.Map() function to replace the character "a" with "@".

Code
Output
Loading...

All contributors

Contribute to Docs

Learn Go on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn how to use Go (Golang), an open-source programming language supported by Google!
    • Beginner Friendly.
      6 hours