TutorialEdge

Challenge 01 - Type Assertions

Welcome everyone to the discussion thread for the first Go challenge posted to the site :tada:

Feel free to show us how you solved the challenge by posting your solutions below!

Solution:

package main

import (
  "fmt"
)

// Developer struct
type Developer struct {
  Name string
  Age int
}

func GetDeveloper(name interface{}, age interface{}) Developer {
  var dev Developer
  dev.Name = name.(string)
  dev.Age = age.(int)
  return dev
}

func main() {
  fmt.Println("Hello World")

  var name interface{} = "Elliot"
  var age interface{} = 26

  dynamicDev := GetDeveloper(name, age)
  fmt.Println(dynamicDev.Name)
}

Noticed a weird bug.

Getting a

command-line-arguments

/tmp/challenge585416135/main.go:16:23: syntax error: unexpected {, expecting name or (
/tmp/challenge585416135/main.go:17:21: syntax error: unexpected {, expecting name or (

if code is typed line by line.

See below:

                var dev Developer
                dev.Name = name.(string)
                dev.Age = age.(int)
                return dev

If the same code is pasted, the error does not occur.

Could it be a weird character pasted in?

I guess I will have to add some tests around validating the text in the code is valid.

func GetDeveloper(name interface{}, age interface{}) Developer {

Name := name.(string)

Age := age.(int)

return Developer{Name, Age}

}