Go by Example Closures ~ Errors 2015-03-30, Sam Jo.

Slides:



Advertisements
Similar presentations
The TeachScheme! Project Adelphi University Brown University Northeastern University University of Chicago University of Utah Worcester Polytechnic Institute.
Advertisements

Chapter 6 Data Types
Programming Languages and Paradigms The C Programming Language.
Copyright © 2012 Pearson Education, Inc. Chapter 9 Delegates and Events.
IT253: Computer Organization Lecture 6: Assembly Language and MIPS: Programming Tonga Institute of Higher Education.
C++ Basics Variables, Identifiers, Assignments, Input/Output.
Names and Bindings.
Introduction to Computing Concepts Note Set 7. Overview Variables Data Types Basic Arithmetic Expressions ▫ Arithmetic.
Various languages….  Could affect performance  Could affect reliability  Could affect language choice.
Chapter 10 Implementing Subprograms. Copyright © 2012 Addison- Wesley. All rights reserved. 1-2 Chapter 10 Topics The General Semantics of Calls and Returns.
CSSE 332 Functions, Pointers in C. 2 Functions - why and how ? If a problem is large If a problem is large Modularization – easier to: Modularization.
Introduction to ML - Part 2 Kenny Zhu. What is next? ML has a rich set of structured values Tuples: (17, true, “stuff”) Records: {name = “george”, age.
Run time vs. Compile time
1 Run time vs. Compile time The compiler must generate code to handle issues that arise at run time Representation of various data types Procedure linkage.
EXPLOIT STUDY USING CTF WHOAMI SYMNOISY Symnoisy.tistory.com 3c1c.tistory.com Pwner Reverser KSIA.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Chapter TwelveModern Programming Languages1 Memory Locations For Variables.
ISLab Flash Team Flash File System Ban,A US Patent 5,404,485 한국외국어대학교 컴퓨터및정보통신공학과 박 성 환.
C# 3.0 & LINQ 천호민 Visual C# MVP zmeun.tistory.com.
Comp 245 Data Structures Recursion. What is Recursion? A problem solving concept which can be used with languages that support the dynamic allocation.
© 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5/e Starting Out with C++: Early Objects 5 th Edition Chapter 2 C++
10/16/2015IT 3271 All about binding n Variables are bound (dynamically) to values n values must be stored somewhere in the memory. Memory Locations for.
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
1 CS 007: Introduction to Computer Programming Ihsan Ayyub Qazi.
Java Programming Java Basics. Data Types Java has two main categories of data types: –Primitive data types Built in data types Many very similar to C++
Types(1). Lecture 52 Type(1)  A type is a collection of values and operations on those values. Integer type  values..., -2, -1, 0, 1, 2,...  operations.
Session 7 Methods Strings Constructors this Inheritance.
Simulink 강의 노트 작성 일자 : 2007, 01, 30 저 자 : 임 종수. 강의 순서 -- Section Simulink 의 특징과 install 시 주의사항. 2. simple simulink model 개발. 3. simulink 의 계산 방법.
프로그래밍 기초와 실습 Chapter 6 The Fundamental Data Types.
C++ 0x 달려 BOA 요 ~ 아. 꿈. 사 비밀 모임 발표 : 김연기. 발표자 는 뉴규 ? 김연기 아. 꿈. 사 오후반 스터디 그룹 장소 예약 담당 (Pattern Oriented Software Architecture 2) ~ Microsoft Visual.
영상 획득 영상 저장 카메라 파라메터 커스텀 이미지
Real-Time Computing and Communications Lab., Hanyang University Real-Time Computing and Communications Lab., Hanyang University.
Concepts of programming languages Chapter 5 Names, Bindings, and Scopes Lec. 12 Lecturer: Dr. Emad Nabil 1-1.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 실 습실 습 7 WEEK 1 – 구조체 (STRUCTURES)
Chapter 5 Data Types SANGJI University KO Kwangman
7 주 강의 Functions. Top-down programming type function_name (parameter_list) { declarations statements } int factorial(int n) { int i, product = 1; for.
Buffer Overflow 공격의 이해 송치현 제 11회 해킹캠프.
RUNTIME ENVIRONMENT AND VARIABLE BINDINGS How to manage local variables.
CPS120: Introduction to Computer Science Data Structures.
ISBN Chapter 10 Implementing Subprograms.
9-4 The Shifter  Shifter shifts the value on Bus B  Right shift and Left shift Bidirectional shift register with parallel load First clock pulse 에 Bus.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 실 습실 습 6-2 WEEK 2 - FUNCTIONS THAT RETURN A VALUE.
POINTERS IN C. Introduction  A pointer is a variable that holds a memory address  This address is the location of another object (typically another.
방명록 제작. 목차  기본 레이아웃  DB 구조  방명록 구조  코드 설명  화면 설명.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
Procedure Definitions and Semantics Procedures support control abstraction in programming languages. In most programming languages, a procedure is defined.
Int fact (int n) { If (n == 0) return 1; else return n * fact (n – 1); } 5 void main () { Int Sum; : Sum = fact (5); : } Factorial Program Using Recursion.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 실 습실 습 4.
Smart TV Search. 첫 회첫 회 마지막 회 다음 회 문제점 : 검색 키워드에서 직접적인 NER 매핑이 불가능. Naver 연관 검색.
Imperative Programming C. Imperative Programming Heart of program is assignment statements Aware that memory contains instructions and data values Commands:
CHAPTER 8. MEMORY MANAGEMENT SUNG-DONG KIM DEPT. OF COMPUTER ENGINEERING, HANSUNG UNIVERSITY.
CHAPTER 4 VARIABLES & BINDING SUNG-DONG KIM DEPT. OF COMPUTER ENGINEERING, HANSUNG UNIVERSITY.
FASTFAST All rights reserved © MEP Make programming fun again.
Pointers A variable that holds an address value is called a pointer variable, or simply a pointer.  What is the data type of pointer variables? It’s not.
Golang Functions Functions allow modularization func MySqrt(f float64) (v float64, ok bool) { if f >= 0 { v,ok = math.Sqrt(f), true } return v, ok //or.
CSCI206 - Computer Organization & Programming
Object Lifetime and Pointers
Pointers What is the data type of pointer variables?
Chapter 4 Variables & Binding
Pointers & Arrays.
Implementing Subprograms
Memory Locations For Variables
CSCI206 - Computer Organization & Programming
Pointers and References
Closure Closure binds a first-class function and a lexical environment together This is a complex topic, so we will build up our understanding of it we.
Introduction to C++ Programming Language
Pointers & Arrays.
C++ Programming: review on C: Pointer and malloc
Pointers and References
Presentation transcript:

Go by Example Closures ~ Errors , Sam Jo

내용 Closures Recursion Pointers Structs Methods Interfaces Errors

Closures A closure is a function together with a referencing environment for the non-local variables of that function. 클로져는 그 함수의 지역 변수가 아닌 것들을 위한 참조 환경을 함 께 가지고 있는 함수이다. – By Wikipedia ??????????

Closures in JavaScript function ini() { var name = "Mozilla"; function displayName() { alert(name); } displayName(); } ini(); function makeFunc() { var name = "Mozilla"; function displayName() { alert(name); } return displayName; } var myFunc = makeFunc(); myFunc();

Closures in Go func ini() { name := "Mozilla“ displayName := func() { fmt.Println(name) } displayName() } func makeFunc() func() { name := "Mozilla" displayName := func() { fmt.Println(name) } return displayName; } myFunc := makeFunc() myFunc()

Closures func get5Adder() func() { sum := 0 return func() { sum += 5 fmt.Println(sum) } fiveAdder := get5Adder() fiveAdder() Closure 안에서 외부 변수의 값을 변경 가능하다 ! 그 값은 계속 유지된다 ! <- 5 <- 10

Closures - Exercise 피보나치 수열을 출력해보자 ! func fiboSeq() func() int { …. return func() int { …. }

Closures - Solution func fiboSeq() func() int { a, b := 0, 1 return func() int { a, b = b, a + b return a } func main() { fun := fiboSeq() for i := 0; i < 10; i++ { fmt.Println(fun()) }

Recursion func fact(n int) int { if n == 0 { return 1 } return n * fact(n-1) }

Pointer A pointer is a programming language object, whose value refers to (or "points to") another value stored elsewhere in the computer memory using its address. 다른 값의 메모리 주소를 가리키는 오브젝트 – By Wikipedia C/C++ 에서 나오는 그 포인터 NO Pointer Arithmetic

C 랑 비슷한 문법 *int * 을 붙이면 포인터 타입 *iptr = 해당 메모리 주소에 값 대입 &i i 의 메모리 주소 func zeroval(ival int) { ival = 0 } func zeroptr(iptr *int) { *iptr = 0 } i := 1 fmt.Println("initial:", i) zeroval(i) fmt.Println("zeroval:", i) zeroptr(&i) fmt.Println("zeroptr:", i) fmt.Println("pointer:", &i)

Structs type Animal struct { age int name string } p := Animal{8, “ 냥이 ”} p := Animal{age: 8} p := Animal{} fmt.Println(p.X) C 의 바로 그거, mutable 하다. <- 이렇게 선언해주면 된다. <- 이렇게 객체를 만들면 된다. ( 생략된 field 는 0, false, nil) <- 이렇게 값에 접근하면 된다.

Structs + Pointers ani := Animal{8, “ 냥이 “} ani.age = 4 aniP := &ani aniP.age = 8 fmt.Println(ani) <- struct 변수 앞에 & 을 붙여서 포인터 <- struct 변수와 포인터 모두.(dot) 을 이 용하여 내용에 접근 (C 와 다름 )

Methods func (a *Animal) fakeAge() int { return a.age * 2 } func (a Animal) kill() { a.age = -1 } fmt.Println(ani.fakeAge()) ani.kill(); fmt.Println(ani) fmt.Println(aniP.fakeAge()) aniP.kill(); fmt.Println(aniP) func (p type) name() ret_type { … } 와 같이 선언 type 또는 *type 둘 중에 하나만 선언해도 자동으로 처리 ( 그리고 하나만 선언해야 한다 ) <- 이 코드의 결과는 ?

Methods - Result fmt.Println(ani.fakeAge()) ani.kill(); fmt.Println(ani) fmt.Println(aniP.fakeAge()) aniP.kill(); fmt.Println(aniP) func (a *Animal) kill() { a.age = -1 } 16 {8 냥이 } 16 &{8 냥이 } <- 이렇게 바꾸면 잘 됩니당

Interfaces type name interface { method_name() ret_type } type t struct implement name { } <- 이렇게 선언하면 된다. <- 이렇게 쓰는거 아닙니다. 모든 method 를 구현하기만 하면 됩니다.

Interfaces – Examples More Detail:

Errors Go 는 기본적으로 try/catch/finally 같은 것을 지원하지 않음 ( 그래서 이걸 만든 사람이 있음 -“In Go it’s idiomatic to communicate errors via an explicit, separate return value.” Convention 에 의하면 error object 는 기본 interface 인 error type 을 가져야 하며, 가장 마지막 반환 값에 위치합니다.

Errors - Default func f1(arg int) (int, error) { if arg == 42 { return -1, errors.New(“42!") } return arg + 3, nil } <- error 는 가장 마지막에 위치 <- errors.New 는 error object 생성 <- nil 은 오류가 없음을 표시

Errors - Custom type argError struct { arg int prob string } func (e *argError) Error() string { return fmt.Sprintf("%d - %s", e.arg, e.prob) } func f2(arg int) (int, error) { if arg == 42 { return -1, &argError{arg, "can't work with it"} } return arg + 3, nil } Error interface 는 다음과 같다. type error interface { Error() string } 즉, Error() 만 구현하면 된다 ! - 오류가 발생했을 때 오류 정보를 string 으 로 만들기 위해 호출되는 함수 Error 도 struct 이므로 struct 생성 방법 과 똑같이 만들면 된다.

Errors – How to Use? for _, i := range []int{7, 42} { if r, e := f2(i); e != nil { fmt.Println("f2 failed:", e) } else { fmt.Println("f2 worked:", r) } 딱히 설명이 필요 없다.

Interfaces, Errors - Exercise

Interfaces, Errors – Solution 1 func (i Image) Bounds() image.Rectangle { return image.Rect(0, 0, 256, 256) } func (i Image) ColorModel() color.Model { return color.RGBAModel } func (i Image) At(x, y int) color.Color { return color.RGBA{uint8(x + y), uint8(x - y), 255, 255} }

Interfaces, Errors – Solution 2 type ErrNegativeSqrt float64 func (e ErrNegativeSqrt) Error() string { return fmt.Sprintf("cannot Sqrt negative number: %v", float64(e)) } func Sqrt(x float64) (float64, error) { if (x < 0) { return -1, ErrNegativeSqrt(x) } return math.Sqrt(x), nil }

끝 – 감사합니다.