blob: 2e058be7e6e19526fb24502964b5466d6e3fa86a [file] [log] [blame]
Russ Coxd2cc9882012-02-16 23:50:37 -05001// run
Russ Cox4cf77112009-01-30 14:39:31 -08002
3// Copyright 2009 The Go Authors. All rights reserved.
4// Use of this source code is governed by a BSD-style
5// license that can be found in the LICENSE file.
6
Rob Pike83976e32012-02-19 14:28:53 +11007// Test functions and goroutines.
8
Russ Cox4cf77112009-01-30 14:39:31 -08009package main
10
11func caller(f func(int, int) int, a, b int, c chan int) {
Russ Cox00f9f0c2010-03-30 10:34:57 -070012 c <- f(a, b)
Russ Cox4cf77112009-01-30 14:39:31 -080013}
Russ Cox00f9f0c2010-03-30 10:34:57 -070014
Russ Cox4cf77112009-01-30 14:39:31 -080015func gocall(f func(int, int) int, a, b int) int {
Russ Cox00f9f0c2010-03-30 10:34:57 -070016 c := make(chan int)
17 go caller(f, a, b, c)
18 return <-c
Russ Cox4cf77112009-01-30 14:39:31 -080019}
20
21func call(f func(int, int) int, a, b int) int {
22 return f(a, b)
23}
24
25func call1(f func(int, int) int, a, b int) int {
26 return call(f, a, b)
27}
28
29var f func(int, int) int
30
31func add(x, y int) int {
32 return x + y
33}
34
Russ Cox00f9f0c2010-03-30 10:34:57 -070035func fn() func(int, int) int {
Russ Cox4cf77112009-01-30 14:39:31 -080036 return f
37}
38
39var fc func(int, int, chan int)
40
41func addc(x, y int, c chan int) {
42 c <- x+y
43}
44
Russ Cox00f9f0c2010-03-30 10:34:57 -070045func fnc() func(int, int, chan int) {
Russ Cox4cf77112009-01-30 14:39:31 -080046 return fc
47}
48
49func three(x int) {
50 if x != 3 {
Russ Cox00f9f0c2010-03-30 10:34:57 -070051 println("wrong val", x)
52 panic("fail")
Russ Cox4cf77112009-01-30 14:39:31 -080053 }
54}
55
56var notmain func()
57
Russ Cox00f9f0c2010-03-30 10:34:57 -070058func emptyresults() {}
59func noresults() {}
Rob Pike5e11bb22009-09-14 13:09:53 -070060
61var nothing func()
62
Russ Cox4cf77112009-01-30 14:39:31 -080063func main() {
Russ Cox00f9f0c2010-03-30 10:34:57 -070064 three(call(add, 1, 2))
65 three(call1(add, 1, 2))
66 f = add
67 three(call(f, 1, 2))
68 three(call1(f, 1, 2))
69 three(call(fn(), 1, 2))
70 three(call1(fn(), 1, 2))
71 three(call(func(a, b int) int { return a + b }, 1, 2))
72 three(call1(func(a, b int) int { return a + b }, 1, 2))
Russ Cox4cf77112009-01-30 14:39:31 -080073
Russ Cox00f9f0c2010-03-30 10:34:57 -070074 fc = addc
75 c := make(chan int)
76 go addc(1, 2, c)
77 three(<-c)
78 go fc(1, 2, c)
79 three(<-c)
80 go fnc()(1, 2, c)
81 three(<-c)
82 go func(a, b int, c chan int) { c <- a+b }(1, 2, c)
83 three(<-c)
Rob Pike5e11bb22009-09-14 13:09:53 -070084
Russ Cox00f9f0c2010-03-30 10:34:57 -070085 emptyresults()
86 noresults()
87 nothing = emptyresults
88 nothing()
89 nothing = noresults
90 nothing()
Russ Cox4cf77112009-01-30 14:39:31 -080091}