How to declare a function argument that can accept only int in Go

1 Answer

0 votes
package main

import "fmt"

func AcceptInt(x interface{}) {
    if val, ok := x.(int); ok {
        fmt.Println("It's an int:", val)
    } else {
        fmt.Println("Not an int")
    }
}

func main() {
    AcceptInt(860)
    AcceptInt(3.14)
    AcceptInt("ABCD")
    AcceptInt(true)
    AcceptInt('A')
}



/*
run:

It's an int: 860
Not an int
Not an int
Not an int
Not an int

*/

 



answered Aug 1, 2025 by avibootz
...