Preferred declare / initialize method

I am playing with Google Go now.
There are many ways to declare and / or initialize variables.
Can someone explain the pros / cons of each method (samples, as far as I know, below):

    var strArr0 *[10]string = new([10]string)

    var strArr1 = new([10]string)

    var strArr2 = make([]string,10)

    var strArr3 [10]string

    strArr4 := make([]string,10)

What is your preferred syntax and why?
Thanks, SUCH people!

+3
source share
2 answers

I numbered your examples 1-5 and I will go through them here. Hope this helps!

var strArr0 *[10]string = new([10]string)  // (1)

Here a new array of strings of length 10 is highlighted and returns a pointer to the array.

var strArr1 = new([10]string)  // (2)

This is exactly the same as 1. This is just a shorthand that works due to output like Go. It can be shortened further:

strArr1 := new([10]string)  // (2a)

Where 1, 2, 2a all produce exactly the same result.

var strArr2 = make([]string,10)  // (3)

10. . golang:

make() , , .

make([]T, length, capacity)

, ,   :

make([]int, 50, 100)
new([100]int)[0:50]

, 3 :

var strArr2 = new([10]string)[0:10]  // Slicing an explicitly created array
var strArr2 []string = new([10]string)[0:10]  // Explicitly declaring the type of strArr2, rather than inferring
strArr2 := new([10]string)[0:10]  // Using the := shorthand instead of var

new make , . make , . , , make , .

, :

var strArr3 [10]string  // (4)

, 1, 2 2a.

strArr4 := make([]string,10)  // (5)

, 3.: = .


? , , , , . , :

foo := bar.ToStringArray()

, , :

var foo []string = bar.DoSomethingOpaque()

, - , .

+7

, . , , , . , , , , , - .

, . , , - , ( var io.Reader = os.Open(...)).

(var strArr2 = make([]string,10), strArr4 := make([]string,10) , , .

.

, . :

s := make([]string, 10)
+2

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


All Articles