Original post

This is a question about grammar while 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("%sn", 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 { ... }

thank you sir

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