Nov 112017

ADM

How to convert a char array to a string using Golang

  • November 11 2017
  • ADM

 

 

How to convert a char array to a string using Golang - golang

 

Here is a simple snippet how to convert a char array to a string type in Golang. If you need help how to install Golang check the references links.

Code

To convert the char array to a string the string method was used.

package main

import (
	"fmt"
)

func main() {

	var chars = []byte{97, 98, 99, 100, 101, 102, 103}
	
	/** print the array of chars */
	fmt.Println(chars)

	/** convert char array to string */
	str := string(chars)

	/** print the new string to the console */
	fmt.Println(str)

}

Compile&Run

To compile the code navigate to the file location and run the following command.

$ go build char_array_to_string.go

Then depending if you are on Linux or windows the binary file is created.

To run the application execute the command.

Linux

$ char_array_to_string

Windows

c:\Users\adm\go\tutorials> char_array_to_string.exe

If you want to compile and run the application in one single step run the following command:

go run char_array_to_string.go

Output

Will display the char array and the corresponding string value.

[97 98 99 100 101 102 103]
abcdefg

References