How do I create an array the size of user input? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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?

30th Jul 2022, 11:12 AM
Damian Muszyński
Damian Muszyński - avatar
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.
30th Jul 2022, 1:41 PM
Damian Muszyński
Damian Muszyński - avatar
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
30th Jul 2022, 12:58 PM
🍇 Alex Tușinean 💜
🍇 Alex Tușinean 💜 - avatar
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
30th Jul 2022, 1:02 PM
SoloProg
SoloProg - avatar