2014-07-19 16 views
7

Voglio passare i risultati da una funzione fn() restituendo più valori in una funzione wantx() che accetta più valori. Questo sembra funzionare se il numero di valori accettati da wantx() corrisponde al numero di valori restituiti. Ad esempio, fn() restituisce 2 valori, e want2() accetta 2 valori:errore go - valore multiplo fn() nel contesto a valore singolo

r:= want2(fn(5)) // seems to work fine 

Tuttavia, se voglio i valori di ritorno di fn() di agire come argomenti 2 e 3 del want3(), poi Viene visualizzato un messaggio di errore:

r:= want3(1, fn(5)) // error: multiple-value fn() in single-value context 

In che modo want2() è un contesto a più valori mentre want3() non lo è?

Come faccio a ricevere la chiamata a want3()?

Ecco il programma completo:

package sandbox 

import "testing" 

func want3(fac int, i int, ok bool) int { 
    if ok { 
     return i * fac * 2 
    } 
    return i * fac * 3 
} 

func want2(i int, ok bool) int { 
    if ok { 
     return i * 2 
    } 
    return i * 3 
} 

func fn(i int) (int, bool) { 
    return i, true 
} 

func TestCall(t *testing.T) { 
    // error: multiple-value fn() in single-value context 
    // r := want3(1, fn(5)) 

    r := want2(fn(5)) // works fine 

    if r != 10 { 
     t.Errorf("Call!") 
    } 
} 

risposta

9

Vedi here:

As a special case, if the return parameters of a function or method g are equal in number and individually assignable to the parameters of another function or method f, then the call f(g(parameters_of_g)) will invoke f after binding the return values of g to the parameters of f in order.

No other special cases for function calls are allowed.

+0

afaiu memorizzare i valori di ritorno 'a, b: = Fn (5); want3 (1, a, b); 'è necessario per la valutazione del tipo implicito in a, b. – ABri

Problemi correlati