OneBite.Dev - Coding blog in a bite size

swap a string in Go

Code snippet on how to swap a string in Go

package main

import (
	"fmt"
)

func main() {
	// Initializing the variables
	var str1 string = "Hello"
	var str2 string = "World"

	// Swapping strings
	str1, str2 = str2, str1

	// Printing the swapped strings
	fmt.Println(str1)
	fmt.Println(str2)
}

This program is written in Go, demonstrating how to swap two strings. First, the two strings to be swapped are declared and initialized with the values “Hello” and “World”, respectively. Then, the values of both strings are then swapped by putting each string on the right side of the assignment operator. Finally, the swapped string values are printed to the console to confirm the swap.

go