×

Go Tutorial

Go Basics

Go Variables

Go Literals

Go Type Handling

Go Operators

Go Decision Making

Go Loops

Go Functions

Go String

Go Arrays

Go Slices

Go Maps

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

How to assign string to bytes array in Golang?

Go language | Learn, how to assign a string to the bytes array and how to append a string at the end of the bytes array?
Submitted by IncludeHelp, on October 19, 2021

The simple, easy, and safest way is to assign a string to bytes array is,

[]byte("String_Value")

Consider the below example,

// Go language program to assign string
// to bytes array

package main

import (
	"fmt"
)

// Main function
func main() {
	// Declare a byte array
	var b []byte

	// Assigning the string to bytes array
	b = []byte("Hello, world!")

	// Printing the type and value
	// of bytes array
	fmt.Printf("%T, %v\n", b, b)

	// Appending the string at the end of
	// the bytes array
	b = append(b, []byte("Okay!")...)
	fmt.Printf("%T, %v\n", b, b)
}

Output:

[]uint8, [72 101 108 108 111 44 32 119 111 114 108 100 33]
[]uint8, [72 101 108 108 111 44 32 119 111 114 108 100 33 79 107 97 121 33]

Golang FAQ »

Advertisement
Advertisement


Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.