Golang: Curious Case of Returning Byte Array and Conversion to Byte Slice

package mainimport (
"fmt"
)
func returnByteArray() (array [5]byte) {byteSlice := []byte("Loves you")
copy(array[:], byteSlice[0:5])
return
}
func main() {
byteArray := returnByteArray()
fmt.Println(string(byteArray[:])) // convert byte array to byte slice and string
}
$ go run main.go
Loves
package mainimport (
"fmt"
)
func returnByteArray() (array [5]byte) {byteSlice := []byte("Loves you")
copy(array[:], byteSlice[0:5])
return
}
func returnByteArrayUsual() [5]byte {
byteSlice := []byte("Loves you")
var array [5]byte
copy(array[:], byteSlice[0:5])
return array
}
func main() {
byteArray := returnByteArray()
fmt.Println(string(byteArray[:])) // convert byte array to byte slice and string
byteArray = returnByteArrayUsual()
fmt.Println(string(byteArray[:])) // convert byte array to byte slice and string
}

--

--

--

Writing to soothe the soul, programming to achieve flow

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

2 Approaches to Microservices Monitoring and Logging

Installing SSL Certificate for GeoServer/Jetty

Making “Fit Check” — a JavaScript Dress Up Game

First brainstorm for “Fit Check” user interface

Add custom domain to Firebase

Installing 2 nodes K8s Cluster on RHEL/CentOS 7 Platform

Serverless architecture for banking chatbot

Views, Materialized views, Secure views

Factory Method Pattern 🏡

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Mipsmonsta

Mipsmonsta

Writing to soothe the soul, programming to achieve flow

More from Medium

How To Watch For File Change in Golang

TicTacGo — An Intro to Golang

Dealing with multiple workers - A Go layman approach

A good summary of Go lang basic syntax