GO IDIOMATIC CONVENTIONS EXPLAINED IN COLOR

Similar documents
GO SHORT INTERVIEW QUESTIONS EXPLAINED IN COLOR

Go Forth and Code. Jonathan Gertig. CSC 415: Programing Languages. Dr. Lyle

Variables. Data Types.

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

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

A Fast Review of C Essentials Part I

GO CONCURRENCY BASICS AND PATTERNS EXPLAINED IN COLOR

understanding

Chapter 2: Introduction to C++

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

Let s Go! Akim D le, Etienne Renault, Roland Levillain. June 8, TYLA Let s Go! June 8, / 58

COMP-520 GoLite Tutorial

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

The C++ Language. Arizona State University 1

UEE1302 (1102) F10: Introduction to Computers and Programming

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

BLM2031 Structured Programming. Zeyneb KURT

Tokens, Expressions and Control Structures

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

Computer Programming : C++

INTRODUCTION 1 AND REVIEW

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Lecture 2 Tao Wang 1


Rule 1-3: Use white space to break a function into paragraphs. Rule 1-5: Avoid very long statements. Use multiple shorter statements instead.

Creating a C++ Program

Basic Types, Variables, Literals, Constants

Tranquility Publications. Web Edition MAC

Summary of Go Syntax /

A A B U n i v e r s i t y

Software and Programming 1

4. Structure of a C++ program

Distributed Systems. 02r. Go Programming. Paul Krzyzanowski. TA: Yuanzhen Gu. Rutgers University. Fall 2015

DEPARTMENT OF MATHS, MJ COLLEGE

Java Bytecode (binary file)

C Fundamentals & Formatted Input/Output. adopted from KNK C Programming : A Modern Approach

The Java Language Rules And Tools 3

Pace University. Fundamental Concepts of CS121 1

Key Differences Between Python and Java

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

CS 231 Data Structures and Algorithms, Fall 2016

LECTURE 02 INTRODUCTION TO C++

Basic Syntax - First Program 1

Introduction to C# Applications

CHAPTER 3 BASIC INSTRUCTION OF C++

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad

Full file at

UNIT- 3 Introduction to C++

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Hotmail Documentation Style Guide

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

Data Types and Variables in C language

DATABASE AUTOMATION USING VBA (ADVANCED MICROSOFT ACCESS, X405.6)

IT 374 C# and Applications/ IT695 C# Data Structures

Program Fundamentals

Procedures, Parameters, Values and Variables. Steven R. Bagley

Class #1. introduction, functions, variables, conditionals

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments

BITG 1233: Introduction to C++

VARIABLES AND CONSTANTS

QueueBlock, ReversalADT, LinkedList,CustomerAccount, not MaintainCustomerData

A JavaBean is a class file that stores Java code for a JSP

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

Software and Programming 1

Chapter 2 Basic Elements of C++

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

GO - QUICK GUIDE GO - OVERVIEW

VARIABLES. 1. STRINGS Data with letters and/or characters 2. INTEGERS Numbers without decimals 3. FLOATING POINT NUMBERS Numbers with decimals

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

Functions & Variables !

VENTURE. Section 1. Lexical Elements. 1.1 Identifiers. 1.2 Keywords. 1.3 Literals

An overview of Java, Data types and variables

COLOGO A Graph Language Reference Manual

Issue with Implementing PrimeSieve() in Go

Go Tutorial. Arjun Roy CSE 223B, Spring 2017

C++ TEMPLATES EXPLAINED IN COLOR

Fundamental of Programming (C)

PLT Fall Shoo. Language Reference Manual

C++ Style Guide. 1.0 General. 2.0 Visual Layout. 3.0 Indentation and Whitespace

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

JOSE LUIS JUAREZ VIVEROS com) has a. non-transferable license to use this Student Guide

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

Java+- Language Reference Manual

Course Coding Standards

Chapter 2 Author Notes

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

Introduction to Java Applications

CMAT Language - Language Reference Manual COMS 4115

GOLD Language Reference Manual

CGS 3066: Spring 2015 JavaScript Reference

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

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

developed ~2007 by Robert Griesemer, Rob Pike, Ken Thompson open source

COMP520 - GoLite Type Checking Specification

CROSSREF Manual. Tools and Utilities Library

Get JAVA. I will just tell you what I did (on January 10, 2017). I went to:

CIS 3260 Intro. to Programming with C#

Transcription:

GO IDIOMATIC CONVENTIONS EXPLAINED IN COLOR REVISION 1 HAWTHORNE-PRESS.COM

Go Idiomatic Conventions Explained in Color Published by Hawthorne-Press.com 916 Adele Street Houston, Texas 77009, USA 2013-2018 by Hawthorne-Press.com. All Rights Reserved. No part of this document may be reproduced or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of Hawthorne Press Company.

TABLE OF CONTENTS HAWTHORNE-PRESS.COM...1 INTRODUCTION...4 BASIC CONSTRUCTS...4 PROGRAMS...5 NAMING CONVENTIONS...8 SUGGESTIONS ON CODING...9 REVISION HISTORY...10

GO IDIOMATIC CONVENTIONS EXPLAINED IN COLOR INTRODUCTION The GO Language, as with many languages, has naming conventions for the various textual elements associated with the language. This is a short primer on creating idiomatic Go programs. More extensive versions are available, but this should give a new Go Developer a head start! Code is rendered in blue, comments in green, and rules highlighted in yellow. BASIC CONSTRUCTS Identifiers UTF-8 Characters beginning with a letter or _ and followed by 0 or more letters and digits. Identifiers are case sensitive. Blank Identifier An under-bar by itself is called a blank identifier. It can be used in a declaration or variable assignments, like any other identifier, but is value is discarded. Anonymous There are situations where variables, types, and functions do not require a name, as it will not be used by the following code. These become anonymous values. Filenames All lower case letters or digits, single words preferred, multiple words separated with an under-bar, _. Filenames may start with digits, but may not start with an under-bar. Source Files Contain Go source code lines, of any length, and have a.go extension. Keywords The following 25 keywords are reserved and may not be used in Go-code. break default func interface select case defer go map struct chan else goto package switch const fallthrough if range type continue for import return Var Reserved Identifiers The following 39 identifiers are reserved for system use. These are names of elementary types, constants, nil and built-in functions.

Types: bool byte complex64 complex128error float32 float64 int int8 int16 int32 int64 rune string uint unit8 uint16 uint32 uint64 uintptr Constants: true False iota Zero Value: nil Built-in Functions: append cap close complex copy delete imag len make new panic print println real recover Delimiters Parentheses ( ), brackets [ ], braces {. Punctuation Period., comma,, semicolon ;, ellipse.... Programs Are composed of statements which are made up of keywords, constants, variables, operators, types, and functions. These are interspersed with non-functional constructs such as comments and spacing. PROGRAMS Minimal Working Program The often heralded hello world program is an example. Source File hello.go: package main import fmt func main() { fmt.println( hello, world! )

Package Every Go file belongs to only one package. A package may contain many Go files. This means the package name and filename are not always the same. Package names are written in lower case and should be one word Import Allows access to the exported objects from the imported packages. Func Introduces a function. A function may or may not have parameters, followed by Brace pair enclosing the statements comprising the function body. Main() - This is a mandatory function for standalone programs. It is always located within package main and is the normal start of any user program. Inline Comments A double slash anywhere on a line indicates the start of a comment and it continues until end-of-line. a := 100 // Length of pool // This function calculates the minimum pool value. Block Comments Starts with a slash asterisk pair and the comment terminates with an asterisk slash pair. This construct can and usually does span multiple lines. /* This function calculates the minimum pool value. */ /* */ This function calculates the minimum pool value. All comments should be complete sentences ending with a period or other punctuation. This will improve the output readability produced by Godoc. See section on Godoc Comments below for more information GO documentation. Exported Objects Identifiers are only visible outside the package if they start with a capital letter. Identifiers starting with lower case letters are private, only accessible within their package. fmt.println( hello world! ) // Notice that Println is capitalized (Code Works) fmt.println( hello world! ) // Notice that println is not capitalized (Code Fails)

Globals Declarations After the import statement, zero or more variables, types, and constants may be declared. These items will have global scope and can be seen by all elements of the package. package main import fmt const s string = "constant" var _hello = "_HELLO" type Stringer interface { String() string // Global constant string // Global Variable of string // Global Stringer Interface func init() { fmt.println( Initialization ) func main() { fmt.println( hello, world! ) Initialization Function The function init() will perform processing after top level objects are evaluated, but before the function main() is executed. This provides a method for special initializations. This function should proceed the main() function (see above), but it may be placed elsewhere if it seems appropriate. Godoc Comments While comments do not generate code, they are used by Godoc to create documentation and as such do impose some general rules on their content. A comment should proceed the package statement describing the purpose of the package and any functions or data it provides. It must immediately proceed the package statement. The godoc program will provide this information when requested for this package. If a package contains multiple files, the package comment should only be present in one file. A comment should proceed every top level type, var, func, or const and absolutely proceed any exported object. The name of these items should be the first word in the comment. See func main example below. /* Package hello implements a simple hello world! message and exits. */ package main import fmt // main This function prints hello world! and quits. func main() { fmt.println( hello, world! )

NAMING CONVENTIONS Names of Go objects should be short and concise. In general If necessary to use multiple words to name an object, use MixedCaps or mixedcaps depending whether the object is exported or not. Filenames Filenames should single words made up of lowercase letters, numbers and under-bars. Unlike identifiers filenames may start with digits, but may not start with an under-bar. If filenames are made up of multiple words, they should be separated by underbars. For example: collection_file. Method/Function Names - A name of method or function that returns a result should be a noun. If it changes the data of an object, use setnoun. For example: file and setfile. Global Objects Such as constants, variables, and types should be single words that unambiguously identify its purpose. Using multiple words with mixed caps if necessary. Since these objects will generally be used throughout the package their purpose and function should be immediately recognizable. Short Lived Variables Many variables have only function or sub-function scope and are short lived, such as indexes. These variables should named with single letter, or only a couple of letters. For example: I, j, or kb. Error Messages Error strings should be all lower case unless starting with a proper noun or acronyms (ie URL ) and unlike comments no period at the end. Since error messages are often made up of multiple components this will make them more readable. Acronyms - Words in these categories ( URL or NATO ) should always be presented with constant case. Either URL or url, but never Url. Package Names Exported Names should not contain an indication of the package to which they belong, as they will be qualified with the package name when evoked. For example, if your package is mydata, a possible command would be Open not mydataopen. Receiver Names A method s receiver should be one or two letters as it will be used often in most cases. If the receiver s identity is Client then the generally acceptable names would be either c or cl. SUGGESTIONS ON CODING Value, OK Pattern In writing your own functions, if the functions produces errors the programmer should return an error code unless the failure is catastrophic enough for a panic. If value, ok := func(param); ok { Process() If value, err := func(param); err!= nil { return err

Declaring Empty Slices The following is the preferred form: var t []string Slice Preference Slices are almost always preferable to fixed arrays. Indent Error Flow Keep normal code as unindented as possible. Try to handle errors first and indent them so the stand out in the code as exceptions. If err!= nil { // error handling return // or continue, etc // normal processing Empty String Check Check for empty string, not for zero string len. This is inefficient, it calls a function instead of using a simple comparison. If s == {... As you find other coding best practices, and there are many more than these, document them for your own reference. It will help you maintain consistent coding practices.

REVISION HISTORY Date By Section Changes 05/27/2018 C.E. Thornton All Initial Document