dqkf49487 2015-04-03 20:25
浏览 31

Golang中的实现接口

I want to implement the interface shown below. I don't know how to begin. Can someone show me how the functions should be implemented?

package interval
package main

type Interval interface {
    contains(r float64) bool // if r is in x, then true
    average(Y Intervall) (Intervall, error)
    String() string                    //cast interval"[a,b]" to [a,b]
    completecontains(Y Intervall) bool //if y is completely in x, give true
    New(a, b float64) Intervall
    //var a int
}
type Complex struct {
    first int
}

func (c Complex) contains(r float64) bool {
    if a <= r <= b {
        return true
    } else {
        return false
    }
}

func (c Complex) String() string {
    return "a"
}

func (c Complex) length() float64 {
    return 2.3
}

func main() {
}
  • 写回答

2条回答 默认 最新

  • dongxinjun3944 2015-04-03 22:52
    关注

    I can't really tell what you are actually trying to do here, but there were several issues with the code

    1. a and b were not defined, I added them to complex to get it to compile
    2. a <= r <= b is not valid in go, changed that
    3. You had a main, so I assume that you meant this to be the runnable app. Package needs to be called "main" for it to be directly runnable.

    May not be what you want, but it now compiles and runs (but doesn't do anything since main is empty)

    Here it is on play

    package main
    
    //import "fmt"
    
    type Intervall interface {
        contains(r float64) bool // if r is in x, then true
        average(Y Intervall) (Intervall, error)
        String() string                    //cast interval"[a,b]" to [a,b]
        completecontains(Y Intervall) bool //if y is completely in x, give true
        New(a, b float64) Intervall
    }
    
    type Complex struct {
        first int
        a     float64
        b     float64
    }
    
    func (c Complex) contains(r float64) bool {
    
        if c.a <= r && r <= c.b {
            return true
        } else {
            return false
        }
    }
    
    func (c Complex) String() string {
        return "a"
    
    }
    func (c Complex) length() float64 {
        return 2.3
    }
    
    func main() {
    
    }
    
    评论

报告相同问题?