기본 콘텐츠로 건너뛰기

1월, 2015의 게시물 표시

golang math/rand 내의 Int() 호출하여 처리하기

간단하게 3 * 3  에 맞는 것을 배열에 표시하기. 총 9개를 각각 랜덤 모듈을 이용해서 간단하게 배열내에 있는 값으로 배치하기 package main import ( "fmt" "math/rand" ) func main() { fmt.Println(" random test ") var a Cube a.Set(1) fmt.Println(" level", a.Level) fmt.Println(" list ", a.List) a.Set(2) fmt.Println(" level 2 ", a.Level) fmt.Println(" list 2 ", a.List) a.Set(3) fmt.Println(" level", a.Level) fmt.Println(" list ", a.List) } var Pocket [24]int = [24]int{10, 10, 10, 10, 21, 22, 23, 24, 31, 32, 33, 34, 41, 42, 43, 44, 51, 52, 53, 54, 60, 60, 60, 60} var Pocket1 [18]int = [18]int{10, 21, 22, 23, 24, 31, 32, 33, 34, 41, 42, 43, 44, 51, 52, 53, 54, 60} var levelAr [3]int = [3]int{100, 10000, 1000000} var pocket [3]int = [3]int{24, 18, 18} type Cube struct { Level int List  [9]int } func (this *Cube) Set(level int)

golang receiver에 대한 Value 및 Pointer 처리 비교

구조체를 정의하고 메소드 리서버를 포인터나  값으로 정의시 차이점은 실질적은 구조체 정보를 갱신할 수 있는지 여부만 다를 뿐이다. 아래의 처리 결과는 동일한 값을 출력한다. package main import (  "fmt"  "math" ) type Vertex struct {  X, Y float64 } func (v *Vertex) Abs() float64 {  return math.Sqrt(v.X*v.X + v.Y*v.Y) } func main() {  v := Vertex{3, 4}  z := &Vertex{3, 4}  fmt.Println(v.Abs())  fmt.Println(z.Abs()) } // 포인터를 메소드 리시버로 사용할 경우 처리 예시 package main import (  "fmt"  "math" ) type Vertex struct {  X, Y float64 } func (v *Vertex) Abs() float64 {  return math.Sqrt(v.X*v.X + v.Y*v.Y) } //타입을 하나 정의 type entity float32 //타입을 증가하는 메소드를 정의 func (e *entity) inc() {  *e++ } func (e entity) echo() {  fmt.Println(e) } func main() {  v := Vertex{3, 4}  z := &Vertex{3, 4}  fmt.Println(v.Abs())  fmt.Println(z.Abs())            //초기값을 정의  var e entity = 3  e.inc()    //값을 1만큼 증가  e.echo()  /

golang overlide 처리하기

메소드 오버로드 처리하기 위해서는 오버로딩되는 함수를 정의하고 부모를 상속해서 실질적인 주소에 자신의 구조체 주소를 주면 자신의 구조체이 메소드가 호출되어 처리된다. package main import (  "fmt" ) type Shaper interface {  Area() float64 } // Parent Shape type Shape struct {  Shaper } func (s *Shape) Area() float64 {  return 0 } func (s *Shape) Doit() float64 {  return s.Shaper.Area() } type Rectangle struct {  Shape  x float64  y float64 } func (r *Rectangle) Area() float64 {  return r.x * r.y } func main() {  s := new(Shape)  s.Shaper = s  fmt.Println(" parent ", s.Doit())  r := new(Rectangle)  r.Shape.Shaper = r  r.x = 5  r.y = 5  fmt.Println(" child ", r.Doit()) }

golang overload 처럼 처리하기

go 언어에서는 함수명이 같을 경우 재선언 오류를 발생시킨다. 다른 메소드를 만들고 오버로드 처리하도록 설계해서 구현해야 한다. 오버로드 처리를 위해 type switch를 사용해서 들어오는 타입에 따라 메소드 호출하는 처리를 사용한다. 함수나 메소드 인자를 다양하게 처리하려면 []interface{} 로 정의해서 다양한 인자를 받아서 오버로딩 처리하면된다. package main import (  "fmt" ) func main() {  var p Person  p = Person{"dahl"}  var s string = "moon"  fmt.Println(" overloading  ", p.Overload(s))  fmt.Println(" overloading", p.Overload(nil)) } type Person struct {  name string } func (this *Person) Overload(args interface{}) string {  switch args.(type) {  case string:   return this.GetName2("moon")  case nil:   return this.GetName1()  default:   return " no match"  } } func (this *Person) GetName1() string {  return this.name } func (this *Person) GetName2(s string) string {  return this.name }

golang언어에서 web 처리하기 기초

기본 파일 처리 방법   1. 구조체를 만든다.         type Page struct {        Title string           Body  []byte         }   2. 구조체에 구조체를 파일에 저장하는 Save() 메소드를 작성한다.          func (p *Page) save() error { filename := p.Title + ".txt" return ioutil.WriteFile(filename, p.Body, 0600)    }  3. 구조체를 파일을 읽어서 구조체에 저장하는 loadPage()메소드를 작성한다.     func loadPage(title string) (*Page, error) { filename := title + ".txt" body, err := ioutil.ReadFile(filename) if err != nil { return nil, err } return &Page{Title: title, Body: body}, nil     }   4. 구조체를 저장한다.            구조체는 초기화는 구조체 타입 + {필드명:값, 필드명:값, .... }             구조체의 메소드 지정시 리시버를 포인터로 지정했기 때문에 &을 사용하여 주소값으로 넘긴다.  그러면 변수는 포인터 변수로 인식한다.                        p1 := &Page{Title: "TestPage", Body: []byte("This is a sample Page.")}                       구조체의 메소드를 호출 p1.save()   5. 구조체를 호출한다.            파일을 읽어서 구조체에 넣는다.           p2, _ := loadPage("Te

golang에서 struct 구조체를 이용해서 File Read/Write 처리하기

입력 파일을 읽고 구조체에 넣고 구조체를 보고 아웃 파일에 쓰기를 처리한다.    -  구조체를 정의하고 구조체 Get()/Set() 메소드를 정의한다.   -    구조체를 보관하는 Array를 정의한다.    - 파일을 읽어서 구조체 Set() 메소드로 세팅한다    - 구조체 Get() 메소드를 구조체 정보를 읽어 파일에 쓰기한다. package main import ( "bufio" "fmt" _ "io" "log" "os" ) type User struct { id   string name string } func (user *User) Set(any []byte) { user.id = string(any[:13]) user.name = string(any[13:23]) } func (user *User) Get() string { return user.id + user.name + "\n" } func main() { fmt.Println(" exec file read/write ") var arrayusers []*User = make([]*User, 2) filein, err := os.Open("../input.txt") if err != nil { log.Fatal(err) } defer filein.Close() scanner := bufio.NewScanner(filein) i := 0 for scanner.Scan() { user := new(User) text := scanner.Text() user.Set([]byte(text)) arrayusers[i] = user i = i + 1 } if err := scanner.Er

golang bacth processing - file to file

  go 언어 배치 프로그램중에 file to file  처리하기  1. 파일을 오픈하여 한 라인씩 읽어서 전체 파일을 처리한다.  2. 파일을 한 라인씩 쓴다. 3. fmt 패키지에 파일로 처리하는 모듈을 이용한다.     -  Fprintln(출력될 구조체 버퍼, 실제 출력한 데이터)     -  타입을 자동으로 알아서 출력한다. func  Fprintln func Fprintln(w io . Writer , a ...interface{}) (n int , err error ) package main import (      "bufio"      "fmt"      "log"      "os" ) // readLines reads a whole file into memory // and returns a slice of its lines. // 파일을 한 라인씩 읽기 // bufio 패키지의 scanner 구조체를 이용하여 처리한다. // func readLines(path string ) ([] string , error ) {      file, err := os.Open(path)      if err != nil {          return nil , err      }      defer file.Close()      var lines [] string      scanner := bufio.NewScanner(file)      for scanner.Scan() {          lines = append (lines, scanner.Text())      }      return lines, scanner.Err() } // writeLines writes the lines to the gi

golang 에서 Array 를 slice 로 convert 하기

golang에서  Array를  Slice 로 컨버전하면 에러가 발생하므로  slice 로 처리해서 컨버전해야 합니다. copy() 함수를 이용하여 슬라이스를 배열로 할당할 수 있는것도  Array 를 슬라이스로 처리하여 세팅해야 한다. type data struct {      id [ 13 ] byte      name [ 20 ] byte } func (this *data) Set(any [] byte ) {      copy (this.id[:], any[ 0 : 13 ])      copy (this.name[:], any[ 13 : 33 ]) } func main() {          var mapping [] byte = make ([] byte , 33 )      mapping = [] byte ( "0123456789012abcdefghijklmnopqrstuvxyz3456789" )      a := new (data)      a.Set(mapping)      fmt.Println( " id " , string ([] byte (a.id[:])))      fmt.Println( " name " , string ([] byte (a.name[:])))      fmt.Println( " mapping " , string (mapping))      var abb [ 20 ] byte      copy (abb[:], [] byte ( "hello world" ))      fmt.Println( string (abb[:])) }

golang file Read/Write 처리하기

go 언어는 일단 os 패키지를 이용하여 파일이 open/close를 처리한다. os 패키지 create를  이용하여 파일을 생성한다. io 패키지의 EOF 상수를 이용하여 파일이 끝을 처리한다. package main import ( "io" "os" ) func main() { // open input file fi, err := os.Open("../input.txt") if err != nil { panic(err) } // close fi on exit and check for its returned error defer func() { if err := fi.Close(); err != nil { panic(err) } }() // open output file fo, err := os.Create("../output.txt") if err != nil { panic(err) } // close fo on exit and check for its returned error defer func() { if err := fo.Close(); err != nil { panic(err) } }() // make a buffer to keep chunks that are read buf := make([]byte, 1024) for { // read a chunk n, err := fi.Read(buf) // do not read EOF if err != nil && err != io.EOF { panic(err) } // do not read a chunk if n == 0 { break } // write a chunk if _, err := fo

golang 에서 generic 처리하기

go언어에서 제너릭 처리를 위해서는 아래처럼  인터페이스를 정의하고 각 타입별로 구현을 한다. 슬라이스에 각 타입으로 컨버전하여 값을 넣고 슬라이스 순번대로 호출하면 자신의 타입에 맞는 메소들를 호출하여 처리한다. type Integer16 int16 type Integer32 int32 type Calculator interface { Calculate() } func (i Integer16) Calculate() { /* behavior here */ fmt.Println(" Integer16 ", i) } func (i Integer32) Calculate() { /* behavior here */ fmt.Println(" Integer32 ", i) } func main() { container := []Calculator{Integer16(1), Integer32(2)} fmt.Println("container   ", container) container[0].Calculate() container[1].Calculate() } // 결과값 ontainer    [1 2] Integer16  1 Integer32  2

Understanding golang Type . 타입이해하기...

Pre-declared Types   go 언어에서 빌드인으로 정의된 데이터 타입들.   string, number(int, uint, float...), boolean 타입들 Named vs Unnamed Type    go언어에서는 사용자 정의(type T_Int int 등)는 기본적으로 named type 으로 인식한다.   그리고  pre-declared types도 named type으로 인식한다.    unnamed type은 composited 타입들로 []int, *int 등을 별도로 인식한다.    named type 들은 메소드 정의가 가능하지만 unnamed type은 메소드를 만들 수 없다.    type Map map[string]string //this is valid func (m Map) Set(key string, value string){ m[key] = value } //this is invalid func (m map[string]string) Set(key string, value string){ m[key] = value } Underlying Type     모든 타입은 underlying type 을 가집니다.  리터럴과 declared type들은 자신의 타입을  underlying type으로 처리한다.     새로 생성되는 타입들에는 기존의 타입들이 있어야 하고 이 타입들도 항상 underlying type 을 가진다.      type Map map[string]string type SpecialMap Map SpecialMap과 Map이 underlying type은 map[string]string 이다. Assignability      //사용자 정의 타입 type Mystring string // pre-de

[go-lang] interface를 이용해서 구조체들의 메소드를 통합하여 처리하기

 인터페이스의 핵심은 구조체의 인스턴스들을 이용하여 메소드를 처리하도록 한다. ​ 인터페이스 안의 메소드를 구조체의 메소드로 정의시 그 안에 정의된 것을 다 정의해야 한다. ​ 구조체는 인터페이스에 있는 메소드보다 더 많은 것을 정의할 수 있다.   ​ 인터페이스를 이용하여 인스턴스를 생성하고 리턴값으로 인터페이스로 전달하여 동일한 인터페이스로 실질적인 구조체들을 처리한다. package main import (     "fmt" ) type sayer interface {     say() } type AA struct{     name string } func (this *AA) say(){     fmt.Println("==========>AA")     fmt.Println("this name ", this.name) } type BB struct{     *AA     age int } func (this *BB) say(){     fmt.Println("==========>BB")     fmt.Println(" this name ", this.name)     fmt.Println(" this age ", this.age) } ​ // 리턴값으로 인터페이스 타입으로 전달한다. // 인터페이스 가 구조체를 참조하여 구조체의 메소드들을 호출하여 처리​ func ObjectFactory(typeNum int) sayer {     if typeNum ==1 {         obj1 := new(AA)         obj1.name = "dahl"         return obj1     }else{         obj2 := new(BB)         obj2.AA = new(AA)         obj2.AA.name = "

golang에서 constance 정의하는 법- iota 사용하기

 상수정의시  첫번째 상수변수에 지정하면 자동으로 숫자를 배정한다. const ( CategoryBooks = iota // 0 CategoryHealth // 1 CategoryClothing // 2 ) package main  import (     "fmt" ) type AudioOutput int const (     OutMute AudioOutput = iota // 0     OutMono                    // 1     OutStereo                  // 2     _                             // 3과 4는 무시한다.     _     OutSurround                // 5 ) // 비트 연산자를 이용한 할당. //<<는 숫자를 하나씩 좌측으로 이동한다.​ type Allergen int const (     IgEggs Allergen = 1 << iota          // 1 << 0 which is 00000001     IgChocolate                         // 1 << 1 which is 00000010     IgNuts                              // 1 << 2 which is 00000100     IgStrawberries                      // 1 << 3 which is 00001000     IgShellfish                         // 1 << 4 which is 00010000 ) func main() {     fmt.Println(" OutMute  ", OutMute)     fmt.Println(" OutSurrou

golang에서 인터페이스 Type Assertion 처리하기

인터페이스 : Type assertion  인터페이스를 이용하여 메소드가 아닌 일반 변수에 할당하며 변수에 정의된 타입들에 대해 명확히 구분할 수 있다 .    Var  변수명  interface{}  로 정의하면 일반 변수정의 타입들도 전달할 수 있다 .      // 구조체 정의   var  a BB = BB{X:10}  //Type assertion  정의       var  value  interface {}     //  할당      value = a     //value.( 타입 )       fmt.Println( "  type assertion " , value.(BB))  // 출력값  {10}   리턴값을  interface{}  즉  type assertion  을 처리하도록 정의   func  weird(i  int )  interface {} {         if  i < 0 {            return   "negative"        }         return  i   }     func  main() {   var  i = 42        if  w, ok := weird(7).( int ); ok {           i += w       }        if  w, ok := weird(-100).( int ); ok {           i += w       }        fmt.Println( "i =" , i)   }   // 결과값은  49  Type Assertion 을 이용하여 타입값들을 확인이 필요한 경우   var  i = 49   var  myInterface  interface {}       myInterface = i       switch  v := myInterfac