如何将一个指针设置为乘法函数?

huangapple go评论79阅读模式
英文:

How to set one pointer to multiply function?

问题

如何将一个指针设置为乘法函数?

package main

import "fmt"

type Cube struct {
    u int
}

func (h *Cube) space() int {
    return h.u * h.u * h.u
}

func main() {
    h := &Cube{
        u: 10,
    }
    fmt.Println(h.space())

    h.u = 100
    fmt.Println(h.space())
}

第一个println请求返回1000,但是第二个println出错,提示左侧没有新变量的:=,但我想要的是指针使用相同的内容,只是将u的值改为100。

英文:

How can I set one pointer to multiply function?

package main

import "fmt"

type Cube struct {
    u int
}

func (h *Cube) space() int {
        return h.u * h.u * h.u
}

func main() {
        h := Cube {
                u: 10,
        }
        fmt.Println(h.space())

        h := Cube {
                u: 100,
        }
        fmt.Println(h.space())
}

The first request of println give back 1000, but with the second println it goes wrong telling no new variables on left side of :=
but I want the pointer to use all same just the u: to 100 change

答案1

得分: 4

:=有两个作用,它既创建一个变量,又给它赋值。你在第二行试图创建一个名为h的新变量,编译器告诉你它不会创建一个新变量。

只需将:=替换为=。

英文:

:= does two things, it creates a variable and assigns a value to it. You are trying to create a new variable called h in the second line and the compiler is telling you that it would not create a new variable.

Just replace that := with =

huangapple
  • 本文由 发表于 2016年3月2日 00:57:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/35728814.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定