+ 3
How do I create an array the size of user input?
I think I need a constant in my Go code but I dont know how to create it. Can someone help? Scenario: I would like to take an int as input and then create an array of this int size. But array size seems to be only possible to declare by literal or const. But it seems I cant create const from user input. I know I could create a slice instead but slices can change size which is not needed in my case Can I even do it the way I want it?
3 Answers
+ 1
@Alex:
This was my first idea on doing that, but unfortunately it fails at point 2.
var x int
fmt.Scanln(&x)
const y = x
"const initializer x is not a constant"
@SoloProg:
Yes, like I said - I know I can do with slices, its just that I don't want to use them since their feature of being dynamically sized is redundant in my case.
I suppose that we should use arrays as much as possible since them being statically sized would make them more time efficient in usage.
0
What if:
1. You get the input from the user
2. You create a const and assign the value of the variable you used for input to it.
3. You then create the array whose length is the constant's value.
I don't really know Go, but this is just a idea of something you may try
0
Slices
Go provides a make() function to create slices.
This is how you create dynamically-sized arrays.
https://www.sololearn.com/learning/1164/4880/12536/1