How to remove duplicate characters from a string in Golang?

To remove duplicate characters from a string in Go, you can use the following steps:

  1. Convert the string to a slice of characters using the []rune function.
  2. Create an empty map to store the characters as keys with a boolean value to check for duplicates.
  3. Iterate over each character in the slice.
  4. Check if the character already exists in the map. If it does, skip to the next iteration.
  5. If the character is not in the map, add it to the map and append it to a new result slice.
  6. Convert the result slice back to a string using the string function.

Here is an example implementation:

func removeDuplicates(s string) string { runes := []rune(s) uniqueChars := make(map[rune]bool) result := []rune{} for _, char := range runes { if !uniqueChars[char] { uniqueChars[char] = true result = append(result, char) } } return string(result) } func main() { str := "Hello, world!" result := removeDuplicates(str) fmt.Println(result) // Output: Helo, wrd! }

In this example, the removeDuplicates function takes a string as input and returns a new string with the duplicate characters removed. We convert the string to a rune slice, iterate over each character, and append it to the result slice only if it hasn't been added before. Finally, the result slice is converted back to a string.