TutorialEdge

Challenge 02 - Satisfying Interfaces

Welcome, everyone to the discussion thread for the second Go challenge posted to the site on satisfying interfaces!

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

Solution:

package main

type Employee interface {
    Language() string
    Age() int
}

type Engineer struct {
    Name string
}

func (e Engineer) Age() int {
  return 26
}

func (e Engineer) Language() string {
    return e.Name + " programs in Go"
}

func main() {
    // This will throw an error
    var programmers []Employee
    elliot := Engineer{Name: "Elliot"}
    // Engineer does not implement the Employee interface
    // you'll need to implement Age() and Random()
    programmers = append(programmers, elliot)
}
package main

import (
    "math/rand"
    "time"
)

// Employee type
type Employee interface {
    Language() string
    Age() int
}

// Engineer type
type Engineer struct {
    Name string
}

// Language interface method for type engineer
func (e Engineer) Language() string {
    return e.Name + " programs in Go"
}

// Age function
func (e Engineer) Age() int {
    return rand.Intn(100)
}

func main() {
    // Randomize the seed used in rand.Intn to get a new int every time the program runs
    rand.Seed(time.Now().UTC().UnixNano())

    // This will throw an error
    var programmers []Employee

    // Implement interface for type Engineer
    var elliot = Engineer{Name: "Elliot"}

    programmers = append(programmers, elliot)
}
1 Like

package main

type Employee interface {
Language() string
Age() int
Random() bool
}

type Engineer struct {
Name string
}

func (e Engineer) Age() int { return 26 }

func (e Engineer) Language() string {
return e.Name + " programs in Go"
}
func (e Engineer) Random() bool {
return true
}

func main() {
// This will throw an error
var programmers []Employee
elliot := Engineer{Name: “Elliot”}
// Engineer does not implement the Employee interface
// you’ll need to implement Age() and Random()
programmers = append(programmers, elliot)
}

Welcome Monkrus to the community!

Your solution looks good!

1 Like

Thank you, Elliot ! Your tutorials and challenges are a true guiding star .

1 Like

package main

import (
“math/rand”
“fmt”
)

type Employee interface {
Language() string
Age() int
}

type Engineer struct {
Name string
}

func (e Engineer) Language() string {
return e.Name + " programs in Go"
}

func (e Engineer) Age() int {
return rand.Intn(100)
}

func main() {
// This will throw an error
var programmers []Engineer
elliot := Engineer{Name: “Elliot”}
// Engineer does not implement the Employee interface
// you’ll need to implement Age() and Random()
programmers = append(programmers, elliot)
for i := range programmers {
fmt.Println(programmers[i].Language())
fmt.Println(programmers[i].Age())
}
}

1 Like

Welcome to the TutorialEdge community!

Code looks good! :muscle: