error: "declared and not used" even if I assign to it

Issue

I can’t find why below code gives compile error “alive declared and not used”.

func ping(ip string)  {     
    var alive bool
    _, err := exec.Command("ping", "-n 1", "-w 1000", ip).Output()
    if err != nil {
        alive = false
    } else {
        alive = true
    }
}

Solution

The compile error you’re seeing is exactly what is happening. That var alive bool is unused. You declare it and assign a value to it but you never do anything with it.

Here is a playground-friendly modification of your code that will run:

package main

import (
    "fmt"
    "strconv"
)

func main() {
    fmt.Println(isInt("Hello, playground")) // prints false
    fmt.Println(isInt("1234567890")) // prints true
}

func isInt(s string) bool {
    var alive bool
    _, err := strconv.Atoi(s) // simply to demonstrate an error case
    if err != nil {
        alive = false
    } else {
        alive = true
    }
    return alive    
}

Notice that I return alive. The function is useless and not something I would suggest in and of itself but it should help illustrate what is missing in your example.

Answered By – Snowman

Answer Checked By – Jay B. (GoLangFix Admin)

Leave a Reply

Your email address will not be published.