The body of the loop is an another block, so using short variable declaration in it will not use the other
variable declared before, outside of the loop, but will create a new other
variable scoped to the body block. Given that, this second other
variable is not used anywhere, because the base != other
condition in the loop refers to the outer other
variable, hence the compile-time error.
Create the expected second variable first, and use simple assignment instead of short variable declaration:
base := "/a/b/c"
other := "/a/b/c/d/e"
for base != other {
var file string
other, file = filepath.Split(other) // "other declared but not used"
fmt.Println(file)
}
Note that the above code will run into an endless loop because filepath.Split()
leaves the trailing slash in other
, so in the next iteration filepath.Split()
will return the same other
(the last dir will not be cut off), and won't ever change again.
To make your code do what you want, you have to cut trailing slashes off, like this:
for base != other {
var file string
other, file = filepath.Split(other) // "other declared but not used"
fmt.Println(file)
if strings.HasSuffix(other, "/") {
other = other[:len(other)-1]
}
}
This will now run and output (try it on the Go Playground):
e
d
Note that the same thing could be achieved with a lot simpler code if you'd use filepath.Base()
to get the last part of the path, and filepath.Dir()
to get the parent folder, like this:
base := "/a/b/c"
other := "/a/b/c/d/e"
for base != other {
fmt.Println(filepath.Base(other))
other = filepath.Dir(other)
}
This outputs the same, try it on the Go Playground.
See related questions:
Why does initializing just one variable in a definition fail, in golang
Why there are two ways of declaring variables in Go, what's the difference and which to use?