Home > Software engineering >  Why am I seeing this error "./main.go:7:6: syntax error: unexpected mars, expecting ("?
Why am I seeing this error "./main.go:7:6: syntax error: unexpected mars, expecting ("?

Time:12-07

Here is my program. I am trying to convert a person's age on mars. It looks everything is fine here but still I am getting this error

package main
import "fmt"

func main() {
var age int
fmt.Scanln(&age)
func mars(age) int{
days := age*365
return days/687
}
mars_age := mars(age)
fmt.Println(mars_age)
}

CodePudding user response:

Try:

package main

import "fmt"

func mars(age int) int {
    days := age * 365
    return days / 687
}
func main() {
    var age int
    fmt.Scanln(&age)

    mars_age := mars(age)
    fmt.Println(mars_age)
}
  • Named func's must be at the same level (i e. main, mars)
  • Function parameters must have types age int

NOTE Go permits anonymous functions (aka lambdas) too. In that case, you could define mars in main and you could assign it to a variable e.g. mars := func(age int) int { ... }

CodePudding user response:

Please see this post on how to use nested functions https://stackoverflow.com/a/42423998/2693654

You need to have something like:

package main
import "fmt"

func main() {
    var age int
    fmt.Scanln(&age)
    x:= func (age int) int {
        days := age*365
        return days/687
    }
    mars_age := x(age)
    fmt.Println(mars_age)
}

CodePudding user response:

Please look at this picture...

  •  Tags:  
  • go
  • Related