doxd96148 2018-06-16 13:44
浏览 75
已采纳

如何将接口实现指针转换为接口指针?

I have a interface:

type Datastore interface {
    InsertString(str string) error
}

I have PostgreSql implementation of this interface:

type DB struct {
    session *sql.DB
}

 func (db *DB) InsertString(str string) error {
    return nil
}

func NewDB(user, password, dbName string) (*DB, error) {
    dbinfo := fmt.Sprintf("user=%s password=%s dbname=%s sslmode=disable",
        user, password, dbName)

    db, err := sql.Open("postgres", dbinfo)
    if err != nil {
        log.Println(err)
        return nil, err
    }

    err = db.Ping()
    if err != nil {
        log.Println("Cannot ping database")
        return nil, err
    }

    return &DB{db}, nil
}

Now I want to get store and use it in my API handlers.

So, I create Environment structure and try to use it:

type Env struct {
    db *store.Datastore
}

func (env *Env) HealthCheckHandler(w http.ResponseWriter, r *http.Request) {
    // A very simple health check.
}

func main() {
    log.Println("Server staring...")

    db, _ := store.NewDB(USER, PASSWORD, DB_NAME)

    env := Env {
        db: db,
    }

    r := mux.NewRouter()
    r.HandleFunc("/health", env.HealthCheckHandler)

    log.Fatal(http.ListenAndServe("localhost:"+PORT, r))
}

But I have a error:

cannot use db (type *store.DB) as type *store.Datastore in field value: *store.Datastore is pointer to interface, not interface

I know, how to fix this. I can use this structure instead of initial:

type Env struct {
    db store.Datastore
}

But I don't want to copy the data.

  • 写回答

1条回答 默认 最新

  • duannaxin9975 2018-06-16 14:02
    关注

    Using

    type Env struct {
        db store.Datastore
    }
    

    is the correct solution. Because store.Datastore is interface type, it is already pointer and youre not coping any data.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀