Introduction

In many programming languages, including Go, you may encounter situations where you need to convert a string to uppercase. Luckily, Go provides a built-in function that makes this task simple and straightforward. In this tutorial, we will explore how to convert a string to uppercase in Go.

To convert a string to uppercase in Go, we can make use of the strings package’s ToUpper function. Here’s an example:

package main

import (
	""fmt""
	""strings""
)

func main() {
	str := ""hello, world!""

	upper := strings.ToUpper(str)
	fmt.Println(upper)
}

In the above code, we import the fmt and strings packages, which provide the necessary functions for working with strings. We declare a variable str and assign it the value of ““hello, world!””.

We then use the ToUpper function from the strings package to convert the string str to uppercase. The result is stored in the upper variable. Finally, we print the uppercase string using fmt.Println.

When you run the code, the output will be:

HELLO, WORLD!

As you can see, the ToUpper function converts all the characters in the string to their uppercase counterparts.

It’s important to note that this method creates a new string with the uppercase characters, rather than modifying the original string. This is because strings in Go are immutable, meaning they cannot be changed once created. If you need to store the uppercase string in a new variable, like in the example above, make sure to assign the result of ToUpper to a new variable.

If you want to convert a string to lowercase, you can use the ToLower function from the strings package in a similar manner.

I hope you found this tutorial helpful! Now you can easily convert strings to uppercase in your Go programs.