Golang Beginner's syntax question

This is a question about grammar while go lang studying.

Post a new topic because an error occurred while using “range for”

I can’t speak English well so I show it in c++ code.

Intended Code (modern c++)

std::vector<std::string> buffer = {"test", "test2", "test3"};
for ( auto &it : buffer) 
  printf ("%s", buffer.c_str());

Error occurred after compile

	buffer := [...]string{"hehe", "hoho"}

	for s := range buffer {
		fmt.Printf("%s\n", s)
	}
result ==>
%!s(int=0)
%!s(int=1)

Why this is happening?"

The “for range” syntax “returns” the index of the item when used with single return, or the key when iterating over a map.

To get the value, you need to use two element form:

for indexOrKey, value := range input { ... }
1 Like

thank you sir

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.