Why is it not possible to convert the [Size] byte to a string in Go?

I have a dimensional byte array that I got after executing md5.Sum() .

 data := []byte("testing") var pass string var b [16]byte b = md5.Sum(data) pass = string(b) 

Error:

 cannot convert b (type [16]byte) to type string 

I find a solution to this problem

Change to:

 pass = string(b[:]) 

But why can't he use it like that?

 pass = string(b) 
+6
source share
1 answer

The short answer is that the Go language specification does not allow this.

Quote from Go Language Specification: Conversions :

The non-constant value of x can be converted to type T in any of these cases:

  • x assigned to T
  • x type and T have the same base types.
  • x type and T are unnamed pointer types, and their base pointer types have the same base types.
  • x type and T are integers or floating point.
  • x type and T are complex types.
  • x is an integer or fragment of bytes or runes, and T is a string type.
  • x is a string, and T is a fragment of bytes or runes.

The specification allows the conversion of a piece of bytes or runes to string , but not an array of bytes.

Long answer

There are different types in Go arrays and slices. The size of the array is part of the type.

Slices are much more general than arrays, and converting an array to a slice that represents the same series of values ​​is very simple: arr[:] (and also cheap, the result slice will be shared by the array as a base array, redistribution or copying will not performed).

Because of this, all functions and support are provided for slices, not arrays.

Just the image you want to create a simple function that takes a fragment (with any length) of int numbers and returns the sum of the numbers. Something like that:

 func sum(s []int) (sum int) { for _, v := range s { sum += v } return } 

If you decided to use the array as input, since the length is part of the type, you would limit the usability of your function, it could only accept arrays of the same length:

 func sum2(s [2]int) (sum int) { for _, v := range s { sum += v } return } 

You can call sum2() only with values ​​of type [2]int , but if you have an array of type [3]int , you cannot, because these 2 types are different! You also cannot call sum2() if you only have an int fragment (you cannot access the slice substitution array). In the meantime, you can call the sum() function with all the []int slices, and if you have an array, you can still use it by passing arr[:] your sum() function.

Note:

Also note that converting a “random” fragment of bytes to string most likely not what you want, because a “random” fragment of bytes cannot be a valid UTF-8 byte sequence.

Instead, use the encoding/hex package to convert the result to a hexadecimal string as follows:

 fmt.Println(hex.EncodeToString(b[:])) 
+16
source

Source: https://habr.com/ru/post/981256/


All Articles