Summary of Go Syntax /

Similar documents
GOLD Language Reference Manual

CS313D: ADVANCED PROGRAMMING LANGUAGE

The PCAT Programming Language Reference Manual

Programming for Engineers Iteration

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

Lecture Overview Methods and Interfaces Methods review Interfaces Example: using the sort interface Anonymous fields in structs

Language Reference Manual simplicity

The SPL Programming Language Reference Manual

CS201 Some Important Definitions

Go Cheat Sheet. Operators. Go in a Nutshell. Declarations. Basic Syntax. Hello World. Functions. Comparison. Arithmetic. Credits

Chapter-8 DATA TYPES. Introduction. Variable:

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

Introduction to C# Applications

CSC Web Programming. Introduction to JavaScript

2 nd Week Lecture Notes

C#: framework overview and in-the-small features

Chapter 2: Using Data

Pointers, Dynamic Data, and Reference Types

GraphQuil Language Reference Manual COMS W4115

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Homework #3 CS2255 Fall 2012

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

UNIT- 3 Introduction to C++

Operators. Lecture 3 COP 3014 Spring January 16, 2018

CS4120/4121/5120/5121 Spring 2016 Xi Language Specification Cornell University Version of May 11, 2016

Quick Reference Guide

Ch. 12: Operator Overloading

Lecture 3 Tao Wang 1

Lesson 02 Working with Data Types MIT 31043, Visual Programming By: S. Sabraz Nawaz

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

An Introduction to MATLAB

Data Types and Variables in C language

Lesson 02 Working with Data Types. MIT 31043: VISUAL PROGRAMMING By: S. Sabraz Nawaz Senior Lecturer in MIT

Operators in java Operator operands.

BASIC ELEMENTS OF A COMPUTER PROGRAM

Pierce Ch. 3, 8, 11, 15. Type Systems

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

LECTURE 3 C++ Basics Part 2

M/s. Managing distributed workloads. Language Reference Manual. Miranda Li (mjl2206) Benjamin Hanser (bwh2124) Mengdi Lin (ml3567)

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

Expressions and Casting. Data Manipulation. Simple Program 11/5/2013

COMP520 - GoLite Type Checking Specification

Fundamentals of Programming

COMP520 - GoLite Type Checking Specification

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands

Variables. Data Types.

GO MOCK TEST GO MOCK TEST I

Programming. Elementary Concepts

Reserved Words and Identifiers

by Pearson Education, Inc. All Rights Reserved.

Expressions and Casting

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology

Outline. Performing Computations. Outline (cont) Expressions in C. Some Expression Formats. Types for Operands

CS31 Discussion. Jie(Jay) Wang Week8 Nov.18

Ch. 3: The C in C++ - Continued -

Client-Side Web Technologies. JavaScript Part I

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

CSI33 Data Structures

Introduction to C++ with content from

Exercise 6.2 A generic container class

Full file at C How to Program, 6/e Multiple Choice Test Bank

Introduction to Visual Basic and Visual C++ Arithmetic Expression. Arithmetic Expression. Using Arithmetic Expression. Lesson 4.

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Visual C# Instructor s Manual Table of Contents

FRAC: Language Reference Manual

If we have a call. Now consider fastmap, a version of map that uses futures: Now look at the call. That is, instead of

CIS133J. Working with Numbers in Java

Decaf Language Reference Manual

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

ESCI 386 IDL Programming for Advanced Earth Science Applications Lesson 1 IDL Operators

GO IDIOMATIC CONVENTIONS EXPLAINED IN COLOR

High Performance Computing in C and C++

COMP-520 GoLite Tutorial

Issue with Implementing PrimeSieve() in Go

Index. object lifetimes, and ownership, use after change by an alias errors, use after drop errors, BTreeMap, 309

Object-Oriented Programming. Topic 2: Fundamental Programming Structures in Java

Lecture 9: Lists. Lists store lists of variables. Declaring variables that hold lists. Carl Kingsford, , Fall 2015

XQ: An XML Query Language Language Reference Manual

PROGRAMMAZIONE I A.A. 2017/2018

Lexical Considerations

COMP520 - GoLite Type Checking Specification

Unit 3. Operators. School of Science and Technology INTRODUCTION

[0569] p 0318 garbage

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

Object-Oriented Programming

Program Fundamentals

SECTION II: LANGUAGE BASICS

Operators. Java operators are classified into three categories:

.Net Technologies. Components of.net Framework

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

Quick Reference Guide

Pointers /

a data type is Types

OBJECT ORIENTED PROGRAMMING. Ms. Ajeta Nandal C.R.Polytechnic,Rohtak

Functional Programming. Pure Functional Programming

Fundamental of Programming (C)

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Conditionals !

CSCE 110 PROGRAMMING FUNDAMENTALS

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments

Transcription:

Summary of Go Syntax 02-201 / 02-601

Can declare 1 or more variables in same var statement Variables Can optionally provide initial values for all the variables (if omitted, each variable defaults to the 0 value for its type) Variables are boxes that contain data. The data is of a particular type. The box is labeled with the variable s name. var Name1, Name2, Type = InitialValue1, InitialValue2, The type of the variables (Can be omitted if you provide initial values from which the type can be inferred) Name1, Name2 := EXPRESSION Can abbreviate using the := syntax. At least 1 variable on the left-hand side must be new. Variables have types that never change Uninitialized variables start with their 0 value (i.e. 0, 0.0,, false) You can t declare variables that you don t use

Scope Variables last from when they are declared to the end of the { } block that they are declared in Exception: variables declared as function parameters last for the entire function Global variables (those not in a {} block) last from when they are declared until the program ends. func gcd(a int, b int) int {!! if a == b {!!! return a!! }!! var c int!! if a > b {!!! c = a - b!!! return gcd(c, b)!! } else {!!! c = b - a!!! return gcd(a, c)!! }! } variable c created variable c destroyed

Types Basic Numeric and logical types int, int8, int16, int32, int64! uint, uint8, uint16, uint32, uint64! bool! float32, float64 List types: arrays (fixed size), slices (variable size), strings (like []int8) [N]Type! []Type! string Maps: relate unique keys of Type1 to values of Type2. Any type where == is defined can be a key type. Structures: a grouping of a small number of variables Pointers: a reference to a variable of type Type map[type1]type2 struct {!! N1 T1!! N2 T2!! N3 T3! } *Type

Types, 2 Types can be composed to create complex data structures: map[int]struct{id int; n []*map[string]int} a map from ints to structs, each containing an int field id and a field n that is a slice of pointers to maps from strings to ints New names for types can be provided via the type statement: type Name Type type S struct {id int; n []*map[string]int} type EmployeeId int

Slices & Arrays var slice []Type []Type declares a slice with elements of type Type slice = make([]type, Length) slices start out as nil, you must call make to create the actual slice. len(slice) the length of slice S can be obtained with len(s) var array [10]Type Arrays are slices with an explicit length (that is known at compile time) slice[i]! array[j] access the I and Jth elements of slices an arrays. I and J can be arbitrary integer expressions (i.e. 3*a + 7*b) Elements are numbered starting at 0 It s an error to try to use an index greater than the size of the slice or array. It s almost always better to use a slice instead of an array.

Maps var Name map[keytype]valuetype Declare a map from KeyType to ValueType Name = make(map[keytype]valuetype) Map variables start as nil Must call make to create the map Name[Key] = Value! fmt.println(name[key]) Set and access elements in maps like arrays and slices v = Name[Key]! v, ok = Name[Key] Check if key present by trying to extract 2 values from the array; second value will be true if Key is in Name delete(name, Key)! len(name) Remove an item with delete Get number of items with len

Structs Group together related variables to create a logical, composite object. struct {!! N1 T1!! N2 T2!! N3 T3! } type Name struct {!! N1 T1!! N2 T2!! N3 T3! } Nearly always used in a type statement to give a name to the struct. Access fields using the. syntax: S.F1 = 3! fmt.println(s.f2)

Composite Literals Specify initial values for composite types (arrays, slices, maps, structs) using the general syntax: ListType{value1, value2, value3, }! MapOrStructType{key1:value1, key2:value2, } Examples: []int{3,4,1,5,6,-6}!!!!! // slice literal! [5]uint{3,4,1,5,6}!!!!! // array literal! map[string]int{ a :3, b :7}!! // map literal! Contact{name: Eric, age:37}!! // struct literal

Pointers Pointers hold the addresses of other variables. var pname *Type Declare pointers by using type *Type Pointers start out nil pname = &i Use the & operator to get the address of a variable to store into a pointer *pname Use *PointerName to follow the pointer (called dereferencing )! *PointerName acts just like the variable it points to. (*pstruct).field pstruct.field These are equivalent in the special case of a pointer to a struct

Type Conversions Type(Expression) Converts the result of Expression into type Type (if possible) var v int! var q float64 = 3.14! v = int(q) To convert a string to a number or vice versa you have to use a library call; Package strconv provides a number of such functions.

Operators +!! addition, string concatenation! -!! subtraction, negation! /!! division, integer division! %!! remainder!! &&!! logical AND!!! logical OR!!!! logical NOT!! ==!! equals!!=!! not equals! <=!! less than or equal to! >=!! greater than or equal to! <!! less than! >!! greater than!! &!! address of! *!! follow pointer ( dereference ) All the operands for an operator must have the same type.

Increment & Decrement Statements For integer variables i : i++!! means increase i by 1! i--!! means decrease i by 1 Assignment Operators a += Expr!! a -= Expr!! a *= Expr!! a /= Expr!! a %= Expr!! means a = a + (Expr)! means a = a - (Expr)! means a = a * (Expr)! means a = a / (Expr)! means a = a % (Expr)

Constants const Name Type = Value Type is optional.! If it s omitted, the constant doesn t have a type and can be used anywhere Value could have been typed directly Can group together several constant definitions const (!! Name1 Type1 = Value1!! Name2 Type2 = Value2!! //! ) Best practice: declare constants for any non-trivial numbers you have in your code.

Import, main() You code starts by running the main() function. You can import packages to access functions and types they include via: import packagename!! import (!! packagename1!! packagename2!! //! ) The functions from package P are accessible via P.FunctionName

Flow Control: Conditionals if BooleanExpression {!! // statements T! } else {!! // statements F! } If BooleanExpression is true do statements T otherwise do statements F switch Value {! case V1:!! // statements! case V2:!! // statements! case V3, V4:!! // statements! default:!! // statements! } Do the first set of statements with a case value (e.g. V1) that matches the switch Value! Do the (optional) default statements if no other case matches.

Flow Control: Loops Do this just before loop starts Execute Statements while BooleanExpr is true Do this in between each iteration (and after the last iteration) for InitStmt ; BooleanExpr ; IncrStmt {!! // Statements! } Any variables declared in the InitStmt have scope of just the for loop One or both of InitStmt and IncrStmt can be empty If both are empty, you can omit the ; If BooleanExpr is empty, it means true

Flow Control: Looping Over Lists and Maps The index or key of the current element The value of the current element (this can be omitted to just loop over the indices) A map, array, slice, or string variable for i, v := range ListVar {!! // Statements! } Use the blank identifier _ if you don t need i If ListVar is a map, the order of the elements is not defined

Functions The receiver type: if present, function must be called using C.Name where C is of type T0 The parameters and their types (if the type is the same as the previous parameter, it can be omitted) The return types (if only 1, the parentheses can be omitted) func (m *T0) Name(param1 T1, param2 T2, ) (RT1, RT2, ) {!! // Statements!! // Including a return statement if any return types were!! // declared! } Functions can return 0 values and can have 0 parameters All possible paths through a function must return a value if a return type is declared Variables of a simple type (int, string, bool, etc) are copied when passed into a function. Arrays are copied when passed into a function Maps and slices are passed by reference: you can change the values in a map or slice within the function.

Design Strategies Top-down: write a function to solve your problem, creating (but not writing) functions for smaller problems as needed. Object-oriented: create types for your real-world entities (users, files, cars) and then write methods that manipulate those entities. Data structuring: choose a way to arrange your data into variables (maps, lists, structs, etc.) that make answering your desired questions easy. Small-to-large: start with a small, simple case, and then add complexity incrementally after you have worked out bugs at each stage.