Home  >  Article  >  Backend Development  >  Go - imported but not used but required

Go - imported but not used but required

PHPz
PHPzforward
2024-02-10 18:18:09486browse

Go - 导入但未使用但必需

php editor Strawberry will introduce you to a common problem: the "imported but not used but required" error that is often encountered in Go programming. This error usually occurs when we import a package but do not use any functions, methods or variables of the package in the code. While this may seem like a harmless warning, it can actually cause some problems. In this article, we will explore the cause of this problem and how to solve it so that you can become more comfortable programming in Go.

Question content

I tried to import the go package, but the following error occurred::

.\data.go:10:2: "github.com/username/test/my-project/model" imported and not used
.\data.go:38:13: undefined: DataModel

These are my go files:

main.go

package main

func main() {consumeApi()}

data.go

package main

import(
    "github.com/username/test/my-project/model"
)

func consumeApi() {
    ...
    var result DataModel
    if err := json.Unmarshal(body, &result); err != nil {
        fmt.Println("Can not unmarshal JSON")
    }
    ...
}
model.go
package model

type DataModel struct {
...
}

go.mod

module github.com/username/test/my-project

go 1.21.0

Can anyone help me solve this problem?

Solution

Replacement

var result DataModel

to

var result model.DataModel

The above is the detailed content of Go - imported but not used but required. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete