2017-03-06 224 views
-1
type MultiplyStruct struct { 
    Number1 int 
} 

func (m MultiplyStruct) Multiply() int { 
    return m.Number1 * number2 
} 

如何將number2傳遞給乘法函數?會是這樣嗎?將變量傳遞給結構函數

var multiplier = MultiplyStruct(10) 
    multiplier.Multiply(20) 

回答

1

認爲這是你想要什麼:

package main 

import (
    "fmt" 
) 

type MultiplyStruct struct { 
    Number1 int 
} 

func (m MultiplyStruct) Multiply(number2 int) int { 
    return m.Number1 * number2 
} 

func main() { 
    multipler := MultiplyStruct{Number1: 10} 
    val := multipler.Multiply(20) 
    fmt.Println(val) 
} 

On Go Playground

+0

那就是它!謝謝 – lol

1

只是一個有趣的除了正確的答案。您可以創建一個curried函數,而不使用結構來存儲整數:

func Multiply(number1 int) (func(int) int) { 
    return func(number2 int) int { 
     return number1 * number2 
    } 
} 

func main() { 
    timesTen := Multiply(10) 
    fmt.Println(timesTen(20)) // => 200 
    timesTwo := Multiply(2) 
    fmt.Println(timesTwo(10)) // => 20 

    fmt.Println(Multiply(2)(3)) // => 6 
}