Working on setting up an EC2 instance with boto, and after the initial boot, I'm going to ssh to the new instance and setup my environment. So, I can use Python or Go, so here's an example of using go to script shell commands from the golang-nuts group
package main
import (
"fmt"
"exec"
"bytes"
)
func main() {
cmd := "/bin/sh"
args := []string{cmd, "-c", "ls passwd"}
dir := "/etc"
p, err := exec.Run(cmd, args, nil, dir,
exec.DevNull, exec.Pipe, exec.PassThrough)
if err != nil {
return
}
var b bytes.Buffer
_, err = b.ReadFrom(p.Stdout)
if err != nil {
return
}
err = p.Close()
if err != nil {
return
}
fmt.Println(b.String())
}
swig -go
Working through the Go SWIG tutorial :
Using two files: example.c and example.i
/* File : example.c */
#include <time.h>
double My_variable = 3.0;
int fact(int n) {
if (n <= 1) return 1;
else return n*fact(n-1);
}
int my_mod(int x, int y) {
return (x%y);
}
char *get_time()
{
time_t ltime;
time(<ime);
return ctime(<ime);
}
%module example
%{
/* Put header files here or function declarations like below */
extern double My_variable;
extern int fact(int n);
extern int my_mod(int x, int y);
extern char *get_time();
%}
extern double My_variable;
extern int fact(int n);
extern int my_mod(int x, int y);
extern char *get_time();
________________________________________________________
% gcc -c -fpic example.c
% gcc -c -fpic example_wrap.c
% gcc -shared example.o example_wrap.o -o example.so
% 6g example.go
% 6c example_gc.c
example_gc.c:14 6c: No such file or directory: runtime.h
Using two files: example.c and example.i
/* File : example.c */
#include <time.h>
double My_variable = 3.0;
int fact(int n) {
if (n <= 1) return 1;
else return n*fact(n-1);
}
int my_mod(int x, int y) {
return (x%y);
}
char *get_time()
{
time_t ltime;
time(<ime);
return ctime(<ime);
}
______________________________________________
/* example.i */%module example
%{
/* Put header files here or function declarations like below */
extern double My_variable;
extern int fact(int n);
extern int my_mod(int x, int y);
extern char *get_time();
%}
extern double My_variable;
extern int fact(int n);
extern int my_mod(int x, int y);
extern char *get_time();
________________________________________________________
Then, according to the instructions in http://www.swig.org/Doc2.0/Go.html#Go
% swig -go example.i% gcc -c -fpic example.c
% gcc -c -fpic example_wrap.c
% gcc -shared example.o example_wrap.o -o example.so
% 6g example.go
% 6c example_gc.c
example_gc.c:14 6c: No such file or directory: runtime.h
After reading golang-nuts thread:
% 6c -I ${GOROOT}/pkg/${GOOS}_${GOARCH}
-D_64BIT example_gc.c
This works.
what does an Amazon EC2 instance cost per month?
Output:
Small instance:
variable cost per month: 21.84
fixed cost per month: 9.72
Monthly small: 31.56
Large instance:
vairiable cost per month: 87.36
fixed cost per month: 38.89
Monthly Large: 126.25
Playing with Strings
Received learninggo yesterday and playing around with formatting strings.
Output:
Using the string: "Hello this is Greg" does this have the prefix:He?: true
and how many non-overlapping occurrances of "is?": 2
Hello 23
Hello 23
-23 int
Go-syntax representation of the value:&main.T{a:7, b:-2.35, c:"abc"}
Go-syntax representation of the type of the value:*main.T
Type:[]string Go-rep of the val:[]string{"Hello", "this", "is", "Greg"}
Hello
this
is
Greg
Also started embedding source on this blog using bitbucket's "embed" script after pushing the source code files from my local computer. I'm using gofmt, and after seeing how long my code is, I'm going to look and see if there's an option to wrap lines.
Output:
Using the string: "Hello this is Greg" does this have the prefix:He?: true
and how many non-overlapping occurrances of "is?": 2
Hello 23
Hello 23
-23 int
Go-syntax representation of the value:&main.T{a:7, b:-2.35, c:"abc"}
Go-syntax representation of the type of the value:*main.T
Type:[]string Go-rep of the val:[]string{"Hello", "this", "is", "Greg"}
Hello
this
is
Greg
Also started embedding source on this blog using bitbucket's "embed" script after pushing the source code files from my local computer. I'm using gofmt, and after seeing how long my code is, I'm going to look and see if there's an option to wrap lines.
http://www.engineyard.com/blog/2009/ready-set-go/
Interfaces
Interfaces are just a collection of function signatures. Here’s an example of interface use taken from the IO library:
type Reader interface {
Read(p []byte) (n int, err os.Error);>
}
type Writer interface {
Write(p []byte) (n int, err os.Error);
}
This is nothing too earth shattering if you’re familiar with Java. If you’re used to Ruby, this is something a little different: actually having to codify the protocols to which your objects conform (see Jim Weirich’s RubyConf 2009 talk for a discussion of this).
Making the connection between interfaces and the types that implement them is just the opposite. It’s implicit—as it is in Ruby et.al.— not explicit, as it is in Java. For example here is something that can be used whenever a Reader is expected:
type limitedReader struct {
r Reader;
n int64;
}
func (l *limitedReader) Read(p []byte) (n int, err os.Error) { ... }
This example also shows declaring a variable (a struct member in this case) of an interface type.
Interfaces
Interfaces are just a collection of function signatures. Here’s an example of interface use taken from the IO library:
type Reader interface {
Read(p []byte) (n int, err os.Error);>
}
type Writer interface {
Write(p []byte) (n int, err os.Error);
}
This is nothing too earth shattering if you’re familiar with Java. If you’re used to Ruby, this is something a little different: actually having to codify the protocols to which your objects conform (see Jim Weirich’s RubyConf 2009 talk for a discussion of this).
Making the connection between interfaces and the types that implement them is just the opposite. It’s implicit—as it is in Ruby et.al.— not explicit, as it is in Java. For example here is something that can be used whenever a Reader is expected:
type limitedReader struct {
r Reader;
n int64;
}
func (l *limitedReader) Read(p []byte) (n int, err os.Error) { ... }
This example also shows declaring a variable (a struct member in this case) of an interface type.
Some of Andre Gerrand's blog on Go Maps
Output:
Bob 17
Alice 21
the value mapped to key Alice: 21
the value mapped to key Bob: 17
c 0
d, okd: 21 true
e, oke: 0 false
f, okf: 0 false
Output:
Bob 17
Alice 21
the value mapped to key Alice: 21
the value mapped to key Bob: 17
c 0
d, okd: 21 true
e, oke: 0 false
f, okf: 0 false
concatenate strings in Go
Following along with a discussion on golang-nuts mailing list.
Go requires you to be explicit when making
allocations. The vector package provides support for Python-like
managed lists:
import "container/vector"
The vector package implements containers for managing sequences of elements. Vectors grow and shrink dynamically as necessary.
Some of the go spec pertaining to this discussion:
Making slices, maps and channels
Slices, maps and channels are reference types that do not require the extra indirection of an allocation with new. The built-in function make takes a type T, which must be a slice, map or channel type, optionally followed by a type-specific list of expressions. It returns a value of type T (not *T). The memory is initialized as described in the section on initial values (§The zero value).
Call Type T Result
make(T, n) slice slice of type T with length n and capacity n
make(T, n, m) slice slice of type T with length n and capacity m
make(T) map map of type T
make(T, n) map map of type T with initial space for n elements
make(T) channel synchronous channel of type T
make(T, n) channel asynchronous channel of type T, buffer size n
The arguments n and m must be of integer type. A run-time panic occurs if n is negative or larger than m, or if n or m cannot be represented by an int.
s := make([]int, 10, 100) // slice with len(s) == 10, cap(s) == 100
s := make([]int, 10) // slice with len(s) == cap(s) == 10
c := make(chan int, 10) // channel with a buffer size of 10
m := make(map[string] int, 100) // map with initial space for 100 elements
Copying slices
The built-in function copy copies slice elements from a source src to a destination dst and returns the number of elements copied. Source and destination may overlap. Both arguments must have identical element type T and must be assignable to a slice of type []T. The number of arguments copied is the minimum of len(src) and len(dst).
Go requires you to be explicit when making
allocations. The vector package provides support for Python-like
managed lists:
import "container/vector"
The vector package implements containers for managing sequences of elements. Vectors grow and shrink dynamically as necessary.
Some of the go spec pertaining to this discussion:
Making slices, maps and channels
Slices, maps and channels are reference types that do not require the extra indirection of an allocation with new. The built-in function make takes a type T, which must be a slice, map or channel type, optionally followed by a type-specific list of expressions. It returns a value of type T (not *T). The memory is initialized as described in the section on initial values (§The zero value).
Call Type T Result
make(T, n) slice slice of type T with length n and capacity n
make(T, n, m) slice slice of type T with length n and capacity m
make(T) map map of type T
make(T, n) map map of type T with initial space for n elements
make(T) channel synchronous channel of type T
make(T, n) channel asynchronous channel of type T, buffer size n
The arguments n and m must be of integer type. A run-time panic occurs if n is negative or larger than m, or if n or m cannot be represented by an int.
s := make([]int, 10, 100) // slice with len(s) == 10, cap(s) == 100
s := make([]int, 10) // slice with len(s) == cap(s) == 10
c := make(chan int, 10) // channel with a buffer size of 10
m := make(map[string] int, 100) // map with initial space for 100 elements
Copying slices
The built-in function copy copies slice elements from a source src to a destination dst and returns the number of elements copied. Source and destination may overlap. Both arguments must have identical element type T and must be assignable to a slice of type []T. The number of arguments copied is the minimum of len(src) and len(dst).
go/doc/GoCourseDay1.pdf OS
Package os provides Exit() and access to file I/O,
command-line arguments, etc. (Flag package
appears shortly.)
Background info:
$godoc -src os Args
var Args []string // provided by runtime
func os.Exit(code int)
Exit causes the current program to exit with the given status code. Conventionally, code zero indicates success, non-zero an error.
Discussion:
if len(os.Args) < 2 { // len(os.Args) is the length of the runtime provided array of command line arguments.
for i := 1; i < len(os.Args); i++ {
fmt.Printf("arg %d: %s\n", i, os.Args[i])
}
for initialization; condition; post suite {suite}
at initialization i = 1, so output is arg 1: firstcommandlineargument
os.Args[i] is an array that's being accessed as a slice? so, here it must be os.Args[1], because initialization i := 1, so it's the second slot of os.Args?
changing:
for i := 0; i < len(os.Args); i++ {
$6g echo.go
$6l echo.6
./6.out one two three
arg 0: ./6.out
arg 1: one
arg 2: two
arg 3: three
so, yes, it looks like it's accessing the second slot of os.Args, and os.Args[0] (what I'm calling slot 1) looks like it's the the file calling the command.
command-line arguments, etc. (Flag package
appears shortly.)
Background info:
$godoc -src os Args
var Args []string // provided by runtime
func os.Exit(code int)
Exit causes the current program to exit with the given status code. Conventionally, code zero indicates success, non-zero an error.
Discussion:
if len(os.Args) < 2 { // len(os.Args) is the length of the runtime provided array of command line arguments.
for i := 1; i < len(os.Args); i++ {
fmt.Printf("arg %d: %s\n", i, os.Args[i])
}
for initialization; condition; post suite {suite}
at initialization i = 1, so output is arg 1: firstcommandlineargument
os.Args[i] is an array that's being accessed as a slice? so, here it must be os.Args[1], because initialization i := 1, so it's the second slot of os.Args?
changing:
for i := 0; i < len(os.Args); i++ {
$6g echo.go
$6l echo.6
./6.out one two three
arg 0: ./6.out
arg 1: one
arg 2: two
arg 3: three
so, yes, it looks like it's accessing the second slot of os.Args, and os.Args[0] (what I'm calling slot 1) looks like it's the the file calling the command.
go tutorial io
a file I'm naming mainio.go
a file I'm naming iopkg.go
$6g iopkg.go
$6g mainio.go
$6l mainio.6
$./6.out
hello, world
can't open file; err=no such file or directory
a file I'm naming iopkg.go
$6g iopkg.go
$6g mainio.go
$6l mainio.6
$./6.out
hello, world
can't open file; err=no such file or directory
go/doc/GoCourseDay1.pdf function literals
As in C, functions can't be declared inside functions -
but function literals can be assigned to variables. Slide 52.
g := func(i int) { //this is a function literal being assigned to a variable. On the next line g(i) is called, so it's like functions can be declared inside of functions by assigning them to variables?
function literals are closures - from go/doc/GoCourseDay1.pdf
Trying out go/doc/GoCourseDay1.pdf.
Trying to make sense of:
func adder() (func(int) int) {
My understanding is: declare function adder() with the function literal func(int) as a parameter of type int
In the main function var f = adder() is declared and then called in successive print statements. Why? I tried:
func main() {
fmt.Print(adder(1))
fmt.Print(adder(1))
}
but this fails with the message:
prog.go:15: too many arguments to function call
prog.go:16: too many arguments to function call
Var f = adder() initializes adder() and then calling f you can pass a variable? and this is because func adder() is declared to accept a function literal that accepts an int argument?
Trying to make sense of:
func adder() (func(int) int) {
My understanding is: declare function adder() with the function literal func(int) as a parameter of type int
In the main function var f = adder() is declared and then called in successive print statements. Why? I tried:
func main() {
fmt.Print(adder(1))
fmt.Print(adder(1))
}
but this fails with the message:
prog.go:15: too many arguments to function call
prog.go:16: too many arguments to function call
Var f = adder() initializes adder() and then calling f you can pass a variable? and this is because func adder() is declared to accept a function literal that accepts an int argument?
Subscribe to:
Posts (Atom)