I am having problem with running Slices right now

hey guys, i am currently new to the golang language!

I just noticed that for line 51 , i have an error which is very strange.
anyone willing to help me out thanks!

Below is the link to my programming

Hi @zaidzac95,

This is line 51:

var names strings.Fields(booking)

var names X is a variable declaration where X must be a type identifier.

To create a variable and assign to it in one step, use the := notation:

names := strings.Fields(booking)

This is the short version of

var names X
names = strings.Fields(booking)

hey ,

thanks for the reply. i have tried to change it but i dont see any changes and the build is still not available?

would there be a bug?

thanks

Sorry, my fault. I answered the question on my mobile and did not run the fixed code.

So when I fix and run the code, I get this error.

./prog.go:52:27: cannot use booking (type []string) as type string in argument to strings.Fields

Which is quite clear: booking is a slice of strings but Fields() expects a single string. I guess “booking” should read “bookings” in this line.

This version of the code runs without errors.

Edit: Of course it has errors, I did not scroll down far enough. Sorry, it’s not my day.

hey @christophberger

there seems to be another problem about the runtime error for slices.

could it because the range is 0 for slices?

thanks

You declare bookings via var, so it becomes a zerovalue that depends on the type, in this case nil. A slice that has the value nil behaves like an empty slice for all intends and purposes.

You never add any item to this slice, so trying to acces the item at index 0 (aka “first item”) will obviously fail.

You should append whatever data you want it to contain before trying to print the first item.

2 Likes

Yeah, you are right, I did not see the error - I didn’t scroll down far enough. @NobbZ has the answer to the index question.

As @NobbZ mentioned, the issue is that you try to refer to a position in the array that doesn’t exist yet, so the assignment for the array before the reference to the value, will resolve the error.

Here is a version of the code that should run successfully.

Please take note, that the program still doesn’t work in the playground because further down in line 53 you are referring to the position 0 in the array (might be good to mention that even in a successful run it won’t always have more than 0 elements in the array, like in a case where the user just pressed Enter and didn’t insert a string of some length, so you might want to consider that as well), and because Go Playground doesn’t accept standard input the way the program expects it, this value is always empty.

standard input, output, and error are instances of naclFile, which uses system calls to interact with the actual files (these are a playground program’s only way to interact with the outside world),

Taken from: Inside the Go Playground - The Go Programming Language