登录
首页 >  Golang >  Go问答

深入理解Golang中的指针

来源:stackoverflow

时间:2024-02-29 16:18:27 219浏览 收藏

golang学习网今天将给大家带来《深入理解Golang中的指针》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习Golang或者已经是大佬级别了,都非常欢迎也希望大家都能给我建议评论哈~希望能帮助到大家!

问题内容

我正在学习 go,我需要了解一些东西。我收到的错误很少。我创建了一个 product 结构并附加了一个 func 。我还得到了一个产品列表作为一个切片。实际上我正在遵循一个例子。我只是尝试向其中添加不同的端点。

我在代码注释中添加了问题。请解释。我需要返回 json 单个对象作为对用户的响应。请指导我。

package data 

type Product struct {
    ID          int     `json:"id"`
    Name        string  `json:"name"`
    Description string  `json:"description"`
    Price       float32 `json:"price"`
    SKU         string  `json:"sku"`
    CreatedOn   string  `json:"-"`
    UpdatedOn   string  `json:"-"`
    DeletedOn   string  `json:"-"`
}

type Products []*Product


func (p *Products) ToJSON(w io.Writer) error {
    e := json.NewEncoder(w)
    return e.Encode(p)
}

func (p *Product) FromJSON(r io.Reader) error {
    d := json.NewDecoder(r)
    return d.Decode(p)
}

var ErrProductNotFound = fmt.Errorf("Product not found")


func GetProduct(id int) (*Product, error) {       // this is returning *Product & err. When I use this in GetProduct in handler func it is giving error
    for _, p := range productList {
        if p.ID == id {
            fmt.Println(p)
            return p, nil
        }
    }
    return nil, ErrProductNotFound
}

var productList = []*Product{    **// Why in example the teacher doing it like this.** []*Product{&Product{}, &Product{}} **what it the reason? Please explain.
    &Product{                             // this gives warning : redundant type from array, slice, or map composite literal. need to understand why**

        ID:          1,
        Name:        "Latte",
        Description: "chai",
        Price:       2.45,
        SKU:         "abc123",
        CreatedOn:   time.Now().UTC().String(),
        UpdatedOn:   time.Now().UTC().String(),
    },
    &Product{
        ID:          2,
        Name:        "Tea",
        Description: "chai",
        Price:       1.45,
        SKU:         "abc1234",
        CreatedOn:   time.Now().UTC().String(),
        UpdatedOn:   time.Now().UTC().String(),
    },
}
package handlers

func (p *Product) GetProduct(rw http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    id, _ := strconv.Atoi(vars["id"])
    p, errr := data.GetProduct(id)  **// cannot use data.GetProduct(id) (value of type *data.Product) as *Product value in assignment**
    errr = p.ToJSON(rw) // **p.ToJSON undefined (type *Product has no field or method ToJSON)**
    if errr != nil {
        http.Error(rw, "could not locate the product", http.StatusBadGateway)
    }
}

解决方案


无法在赋值中使用 data.getproduct(id)(*data.product 类型的值)作为 *product 值

p.tojson 未定义(类型 *product 没有字段或方法 tojson)

这里的问题是,在 getproduct handler 中,变量 p 已经具有与 data.getproduct 函数返回的类型 (*data) 不同的类型 (*handlers.product) .产品)。因此,您可以做的是为将存储 data.getproduct 结果的变量使用不同的名称。

为什么老师会这样做。 []*product{&product{},&product{}} 是什么原因?请解释一下。

一般来说,因为这是根据语言规范初始化结构切片的可用方法之一。老师为什么特意用这个方法呢?除非老师告诉别人原因,否则没有人知道,我当然不知道。

这给出了警告:来自数组、切片或映射复合文字的冗余类型。需要了解原因

因为这是真的,所以根据语言规范,它是多余的,在复合文字表达式中,您可以省略元素和键的类型。

例如以下复合文字的非冗余版本:

[]*product{&product{}, &product{}}

看起来像这样:

[]*Product{{}, {}}

这两个表达式的结果是相同的。

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>