Home > front end >  Simple hello world falls apart in a function with GoLang why?
Simple hello world falls apart in a function with GoLang why?

Time:07-25

Im learning golang have been for a few weeks now and wanted to test my knowledge. This simple Hello World program works within a basic golang func main(){} program.

package main

import "fmt"

func main() {
    h := "h"
    w := "e"
    combinedstring := h   ","   w
    fmt.Println(combinedstring)
}

Yet when I move that code into a function and tell the function what to expect in its parameters and what is being returned the whole thing falls apart.

package main

import (
    "fmt"
)

func printHelloWorld(h string, w string) combinedstring string{
    h := "h"
    w := "e"
    combinedstring := h   ","   w
    return combinedstring
}

func main() {
    fmt.Println(printHelloWorld("hello", "world"))
}

The error I get is: syntax error: unexpected string after top level declaration Which I have no idea what that means even after researching it. Could mean anything...

CodePudding user response:

So there's a few things going on here.

Firstly, when using a named return, you need to wrap it in round brackets.

func myPrefixFunc(msg string) (namedReturn string) {
    namedReturn = fmt.Sprintf("PREFIX: %s", msg)
}

Secondly, in your new function, you're immediately trying to re-declare h and w. They're already declared in the function params, if you wanted to assign values to them (although that would make your function very rigid) you should use = instead of :=.

  • Related