I am new in Go language and want to learn basic fundamental here below I paste example. the problem in this example is I cannot access number variable inside for loop. it shows this error
" number declared and not use "
. Please help me :(
package main
import(
"fmt"
)
func main() {
samlestNumber()
}
func samlestNumber() {
x := []int{
48,96,86,68,
57,82,63,70,
37,34,83,27,
19,97, 9,17,
}
//x = append(x,6,7)
var number int = x[0]
for _,element := range x {
if element < x[0] {
number = element
}
fmt.Println(" :::: ",element)
}
}
It is because you are only declaring and assigning values to number
. You are never actually using it anywhere (i.e. referring to the value it holds in any way). In you code, you can safely remove number
declaration and number = x[0]
and it won't change the program behavior.
The correct implementation however would return the smallest number from the function:
package main
import(
"fmt"
)
func main() {
n := samlestNumber()
fmt.Println("Smallest Number =", n)
}
func samlestNumber() int { // add a return type
x := []int{
48,96,86,68,
57,82,63,70,
37,34,83,27,
19,97, 9,17,
}
//x = append(x,6,7)
var number int = x[0]
for _,element := range x {
// always compare to smallest number. Even if you don't return
// number anymore, you are still accessing the value held by
// the number variable. So even making this change alone will
// make the compiler error go away
if element < number {
number = element
}
fmt.Println(" :::: ",element)
}
return number // return number
}