\documentclass[10pt,a4paper]{article} % Packages \usepackage{fancyhdr} % For header and footer \usepackage{multicol} % Allows multicols in tables \usepackage{tabularx} % Intelligent column widths \usepackage{tabulary} % Used in header and footer \usepackage{hhline} % Border under tables \usepackage{graphicx} % For images \usepackage{xcolor} % For hex colours %\usepackage[utf8x]{inputenc} % For unicode character support \usepackage[T1]{fontenc} % Without this we get weird character replacements \usepackage{colortbl} % For coloured tables \usepackage{setspace} % For line height \usepackage{lastpage} % Needed for total page number \usepackage{seqsplit} % Splits long words. %\usepackage{opensans} % Can't make this work so far. Shame. Would be lovely. \usepackage[normalem]{ulem} % For underlining links % Most of the following are not required for the majority % of cheat sheets but are needed for some symbol support. \usepackage{amsmath} % Symbols \usepackage{MnSymbol} % Symbols \usepackage{wasysym} % Symbols %\usepackage[english,german,french,spanish,italian]{babel} % Languages % Document Info \author{Dmytro (Dmy)} \pdfinfo{ /Title (golang-basics.pdf) /Creator (Cheatography) /Author (Dmytro (Dmy)) /Subject (Golang Basics Cheat Sheet) } % Lengths and widths \addtolength{\textwidth}{6cm} \addtolength{\textheight}{-1cm} \addtolength{\hoffset}{-3cm} \addtolength{\voffset}{-2cm} \setlength{\tabcolsep}{0.2cm} % Space between columns \setlength{\headsep}{-12pt} % Reduce space between header and content \setlength{\headheight}{85pt} % If less, LaTeX automatically increases it \renewcommand{\footrulewidth}{0pt} % Remove footer line \renewcommand{\headrulewidth}{0pt} % Remove header line \renewcommand{\seqinsert}{\ifmmode\allowbreak\else\-\fi} % Hyphens in seqsplit % This two commands together give roughly % the right line height in the tables \renewcommand{\arraystretch}{1.3} \onehalfspacing % Commands \newcommand{\SetRowColor}[1]{\noalign{\gdef\RowColorName{#1}}\rowcolor{\RowColorName}} % Shortcut for row colour \newcommand{\mymulticolumn}[3]{\multicolumn{#1}{>{\columncolor{\RowColorName}}#2}{#3}} % For coloured multi-cols \newcolumntype{x}[1]{>{\raggedright}p{#1}} % New column types for ragged-right paragraph columns \newcommand{\tn}{\tabularnewline} % Required as custom column type in use % Font and Colours \definecolor{HeadBackground}{HTML}{333333} \definecolor{FootBackground}{HTML}{666666} \definecolor{TextColor}{HTML}{333333} \definecolor{DarkBackground}{HTML}{455A64} \definecolor{LightBackground}{HTML}{F3F4F5} \renewcommand{\familydefault}{\sfdefault} \color{TextColor} % Header and Footer \pagestyle{fancy} \fancyhead{} % Set header to blank \fancyfoot{} % Set footer to blank \fancyhead[L]{ \noindent \begin{multicols}{3} \begin{tabulary}{5.8cm}{C} \SetRowColor{DarkBackground} \vspace{-7pt} {\parbox{\dimexpr\textwidth-2\fboxsep\relax}{\noindent \hspace*{-6pt}\includegraphics[width=5.8cm]{/web/www.cheatography.com/public/images/cheatography_logo.pdf}} } \end{tabulary} \columnbreak \begin{tabulary}{11cm}{L} \vspace{-2pt}\large{\bf{\textcolor{DarkBackground}{\textrm{Golang Basics Cheat Sheet}}}} \\ \normalsize{by \textcolor{DarkBackground}{Dmytro (Dmy)} via \textcolor{DarkBackground}{\uline{cheatography.com/163964/cs/34356/}}} \end{tabulary} \end{multicols}} \fancyfoot[L]{ \footnotesize \noindent \begin{multicols}{3} \begin{tabulary}{5.8cm}{LL} \SetRowColor{FootBackground} \mymulticolumn{2}{p{5.377cm}}{\bf\textcolor{white}{Cheatographer}} \\ \vspace{-2pt}Dmytro (Dmy) \\ \uline{cheatography.com/dmy} \\ \end{tabulary} \vfill \columnbreak \begin{tabulary}{5.8cm}{L} \SetRowColor{FootBackground} \mymulticolumn{1}{p{5.377cm}}{\bf\textcolor{white}{Cheat Sheet}} \\ \vspace{-2pt}Not Yet Published.\\ Updated 28th September, 2022.\\ Page {\thepage} of \pageref{LastPage}. \end{tabulary} \vfill \columnbreak \begin{tabulary}{5.8cm}{L} \SetRowColor{FootBackground} \mymulticolumn{1}{p{5.377cm}}{\bf\textcolor{white}{Sponsor}} \\ \SetRowColor{white} \vspace{-5pt} %\includegraphics[width=48px,height=48px]{dave.jpeg} Measure your website readability!\\ www.readability-score.com \end{tabulary} \end{multicols}} \begin{document} \raggedright \raggedcolumns % Set font size to small. Switch to any value % from this page to resize cheat sheet text: % www.emerson.emory.edu/services/latex/latex_169.html \footnotesize % Small font. \begin{multicols*}{3} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Declarations}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{var foo string // declaration with zero value \newline var foo int = 191 // declaration with initial value \newline foo := 191 // shorthand \newline foo, bar := 191 , 23 // shorthand multiple \newline \newline \newline const c = "This is a constant" \newline const ( \newline width = 1920 \newline height= 1080 \newline )} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Types}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{{\bf{Basic Types:}} \newline int, int8, int16, int32, int64 \newline uint, uint8, uint16, uint32, uint64, uintptr \newline float32, float64 \newline complex64, complex128 \newline byte // alias for uint8. ASCII char. var a byte = 'a' \newline rune // alias for int32. Unicode Char \newline string \newline bool \newline \newline {\bf{Composit Types}} \newline struct, array, slice, map, channel \newline \newline {\bf{Interfaces}} \newline Describe behavior of data type} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Functions}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{func main() \{ // main func contains no params and no returns \newline func foo(param0 int, param1, param2 string, ...) (int, string, ...) \{ // func can take multiple params and return multiple values \newline func foo() (res int, code int) \{ // named return \newline res = 2 \newline code = 3 \newline return \newline \} \newline \newline res, code := foo() // execute func and store returned values \newline \newline func foo(a, b, arg ...int) \{\} // variable number of parameters \newline \newline // factory \newline func add(a int) (func(b int) int) \{ // return a function \newline return func(b int) int \{ \newline return a + b \newline \} \newline \} \newline \newline // defer - executed when func exits \newline // When many defer's are declared in the code, they are executed in the inverse order. \newline func foo() \{ \newline fmt.Printf("1") \newline defer f() // function deferred, will be executed latst and print 3. \newline fmt.Printf("2") \newline \} \newline // The defer allows us to guarantee that certain clean-up tasks are performed before we return from a function, for example: \newline // Closing a file stream, Unlocking a locked resource (a mutex), log, ,losing a database connection \newline // Tracing example \newline func foo() \{ \newline callTrace("foo") \newline defer callUntrace("foo") // untracing via defer \newline fmt.Println("foo is being executed") \newline \} \newline \newline // Debugging values \newline func foo(s string)(res int, err error) \{ \newline defer func() \{ \newline log.Printf("foo(\%q) = \textgreater{}\%d, \%v", s, res, err) \newline \}() \newline \newline return 5, nil \newline \} \newline \newline \newline // No Method overload, But we can overload receiver \newline func (a {\emph{Obj1) Add(b Int) Int \newline func (a }}Obj2) Add(b Int) Int} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Misc}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{Go doesn't have casting. Go uses Conversion - bytes need to be copied to a new \newline memory location for the new representation. \newline \newline {\bf{Enums}} \newline const ( \newline ONE= iota \newline TWO \newline THREE \newline ) \newline \newline // Print file full path and line where the code is executed \newline log.SetFlags(log.Llongfile) \newline whereAmI := log.Print \newline whereAmI() \newline \newline \newline // Size \newline size := unsafe.Sizeof(T\{\})} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Interface}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{type ReadWrite interface \{ \newline Read(b Buffer) bool \newline Write(b Buffer) bool \newline \} \newline \newline type Lock interface \{ \newline Lock() \newline Unlock() \newline \} \newline \newline switch t := someVar.(type) \{ \newline case {\emph{Game: \newline fmt.Printf("Game") \newline \newline case }}Unit: \newline fmt.Printf("Unit") \newline \newline default: \newline fmt.Printf("Unexpected type"t) \newline \} \newline \} \newline \newline type File interface \{ \newline ReadWrite \newline Lock \newline Close() \newline \} \newline \newline // Check dynamic var if is of type \newline if v, ok := someVar.(T); ok \{ \newline // ... \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Fmt}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{TBA} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{String and Rune}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{s := "line one \textbackslash{}n line two" // interpreted string \textbackslash{}n - newline \newline s :=\textbackslash{}`line one \textbackslash{}n line two\textbackslash{}` // raw string. no interpretation. no new line for \textbackslash{}n \newline l := len(s) // get string length \newline \newline {\bf{strings}} pkg contains utilities \newline // HasPrefix, HasSuffix, Contains, Index, LastIndex, Replace, \newline // Count, Repeat, ToLower, ToUpper, Trim, TrimSpace, \newline // Fields/Split, Join, Read, ReadByte, ReadRune \newline \newline {\bf{strconv}} pkg contains convertion utilities \newline // Itoa, FormatFloat, Atoi, ParseFloat \newline v, err := strconv.Atoi(s) \newline \newline {\bf{!}} Go strings are immutable - behave like read-only byte slice. \newline // To insert/modify use: \seqsplit{rune(unicode)/byte(ASCII)} slice \newline bs := {[}{]}byte(str) \newline bs{[}0{]} = bs{[}1{]} \newline str = string(bs)} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Struct}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{type foo struct \{ // define new type \newline name string \newline age int \newline \} \newline \newline var f foo // declare instance and init to zero value \newline \newline f := foo \{ // create type instance with literal cunstruction type \newline name: "John", \newline age: 30 \newline \} \newline \newline f := struct \{ // declare a var of unnamed type \newline age: int \newline \}\{ \newline age: 35 \newline \} \newline \newline // Composition \newline type s1struct \{ \newline age int \newline name string \newline \} \newline \newline type s2 struct \{ \newline secondName string \newline s1 \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Array}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{var foo {[}7{]}int // create zero value array length of 7 \newline foo := {[}3{]}int\{10, 20, 30\} // define array length of 3 with values \newline foo := {[}...{]}int\{10, 20\} // compiler calculate length of the array \newline foo := {[}10{]}string\{3: "Three", 4: "Four"\} \newline foo{[}1{]} = 193 // write value \newline a := foo{[}1{]} // read value} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Time}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{t := time.Now() \newline // Duration, Since, Location, Format \newline \newline t := time.Now().UTC() \newline fmt.Println(t.Format("01 Jan 2022 18:34")) // 12 Oct 2022 01:23} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Slice}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{{\bf{Slice}} - is a data structure with 3 fields: \newline 1. * - a pointer to the underlying array \newline 2. len - the length of the slice (indexable by len) \newline 3. cap - capacity of the slice (how long a slice can become) \newline \newline var s {[}{]}string // zero value slice \newline var s {[}{]}string= arr{[}start:end{]} // slice from array \newline s := {[}{]}int\{1,2,3\} // literal \newline s:= make({[}{]}string, len, cap) // create with make \newline \newline {\bf{Multidimentional}} \newline screen:= {[}{]}{[}{]}int\{\} \newline var screen {[}w{]}{[}h{]}int \newline screen{[}2{]}{[}5{]} = 1 // write \newline v := screen{[}2{]}{[}5{]} // read \newline \newline s = s{[}1:{]} // cut 1st element \newline s = s{[}:len(s)-1{]} // cut last element \newline s = s{[}3:5{]} // cut slice - new one from 3rd inclusive to 5th exclusive \newline \newline \newline {\bf{COPY}} \newline func copy(dst, src {[}{]}T) int \newline s := copy(sTo, sFrom) \newline \newline {\bf{ADD/append}} \newline func append(s{[}{]}T, x ...T) {[}{]}T \newline s = append(s, "addValue") // append value \newline s = append(s1, s2...) // append slice \newline \newline {\bf{OPERATIONS}} \newline \newline // Delete at idex i (from i to j) \newline s = append(s{[}:i{]}, s{[}i+1:{]}...) \newline s = append(s{[}:i{]}, s{[}j:{]}...) \newline \newline // Insert a value/range at index i \newline s = append(s{[}:i{]}, append({[}{]}string\{"valueToInsert"\}, s{[}i:{]}...)...) \newline s = append(s{[}:i{]}, append({[}{]}string\{"valueToInsert", "value2ToInsert"\}, s{[}i:{]}...)...) \newline s = append(s{[}:i{]}, append(s2, s{[}i:{]}...)...) // insert existing lice s2 \newline \newline // Stack \newline val, s = s{[}len(s)-1:{]}, s{[}:len(a)-1{]} // Pop \newline s = append(s, val) // Push \newline \newline // Queue \newline val, q = q{[}:1{]}, q{[}1:{]} // Dequeu \newline q = append({[}{]}string\{"value"\}, q...) // Enqueue \newline \newline // Swap \newline s{[}j{]}, s{[}i{]} = s{[}i{]}, s{[}j{]} \newline \newline {\bf{Sort}} \newline sort pkg. ex: sort.Strings(s)} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Maps}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{var m map{[}string{]}int // zero value - nil \newline m := make(map{[}string{]}int) // short \newline m := map{[}int{]}string\{1:"One", 2: "Two"\} \newline \newline m{[}key{]} = val \newline val:= m{[}key{]} \newline \newline if \_, ok := m{[}key{]}; ok \{ // if key is present \newline \} \newline \newline delete(m, key) // delete record \newline \newline // we can range on map with key, value \newline \newline len(map) // get length \newline \newline // Unlike arrays, maps grow dynamically to accommodate new key-values that are added; \newline // they have no fixed or maximum size. However, you can optionally indicate \newline // an initial capacity cap for the map, as in: \newline m := make(map{[}string{]}int, cap) // m := make(map{[}string{]}int, 100)} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Bytes}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{TBA} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Control Structures (if, switch)}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{{\bf{If}} \newline if x \textless{} 0 \{ \newline return err \newline \} else if x == 0 \{ \newline f.Close() \newline \} else \{ \newline a = 5 \newline \} \newline \newline // Pattern to use with true/false condition \newline if n \% 2 == 0 \{ \newline return "even" \newline \} \newline return "odd" \newline \newline // with initialization statement \newline if val := getValue(); val \textgreater{} max \{ \newline return err \newline \} \newline \newline {\bf{Switch}} \newline switch var1 \{ \newline case "a": \newline f() \newline case "b", "c", "d": // multiple values \newline f2() \newline default: \newline f3() \newline \} \newline \newline switch a,b := 3, 4; \{ // with initialization \newline case a \textgreater{} 0: {\bf{fallthrough}} // to execte next \newline case b \textless{} 3: \newline f() \newline \} \newline \newline // switch with multiple conditions \newline switch \{ \newline case i \textless{} 0: \newline f1() \newline case i == 0 \&\& a \textgreater{} 3: \newline f2() \newline case i \textgreater{} 0: \newline f3() \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Loop}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{{\bf{For }} \newline for i := 0; i \textless{} 100; i++ \{\} \newline for i, j := 0, N; i \textless{} j; i, j = i+1, j-1 \{ \} // multiple counters \newline // nested \newline for i:=0; i\textless{}5; i++ \{ \newline for j:=0; j\textless{}10; j++ \{ \newline \} \newline \} \newline \newline // While like \newline for i \textless{} 5 \{ \newline i += 1 \newline \} \newline \newline // infinite loop \newline for \{ \} // another form: for true \{ \} \newline \newline //range \newline for i, val:= range str \{ \newline fmt.Printf("Character on position \%d is: \%c \textbackslash{}n", i, val) \newline \} \newline \newline // we can use {\bf{break}} and {\bf{continue}} to skip execution \newline // there is also {\bf{goto}} and {\bf{label}}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} % That's all folks \end{multicols*} \end{document}