Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Learn Go Language by doing projects

NotificationsYou must be signed in to change notification settings

zaahidali/Learn-go-language

Repository files navigation

Table of Contents

Overview

Welcome to theGo Practice Document, where we'll explore the features and benefits of the Go programming language. This document aims to provide a professional overview of Go and highlight its important aspects.

Introduction to Go

Go is a statically typed programming language that compiles code into binary executables. It offers several key advantages that make it a popular choice among developers:

Pros and Cons

  • Pros:

    • Statically Typed Language:
      • Type checks before compilation
      • Variable types are known before compilation like C, C++ & Java
    • Efficient Memory Management:
      • Fast and reliable
      • Great garbage collector for memory management
    • Extensive Standard Library:
      • Includes packages for HTTP, JSON, file I/O, and more
      • Reduces the need for external dependencies
    • Cross-Compilation:
      • Code can be compiled for different platforms without hassle
    • Concurrency:
      • Uses goroutines and channels for lightweight and efficient concurrency
  • Cons:

    • Smaller Community compared to other languages/frameworks
    • Limited GUI Support
    • Smaller Libraries compared to languages like Ruby
    • Minimalistic Syntax

Basic Code Syntax

To provide a taste of Go, here's an example of the classic"Hello, World!" program in Go:

package mainimport"fmt"funcmain() {fmt.Println("Hello, World!")}

Output:

Hello, World!

Data Types

TypeDescriptionExamples
intInteger numbers.7123, 0, -5, 7023
floatNumbers with decimal points.20.2, 500.123456, -34.23
complexComplex numbers.2+4i, -9.5+18.3i
stringSequence of characters."Hello World!", "1 is less than 2"
boolEither true or false.true, false
byteA byte (8 bits) of non-negative integers.2, 115, 97
runeUsed for characters. Internally used as 32-bit integers.'a', '7', '<'

Go Print Statements

The Go programming language provides several print statement options that allow you to output text and values to the console. Here are three commonly used print statements in Go:

  1. fmt.Println(): This statement prints the given arguments to the console, adding a new line after each print.

  2. fmt.Print(): This statement prints the given arguments to the console without adding a new line. Subsequent prints will be displayed on the same line.

  3. fmt.Printf(): This statement provides more control over the output by using format specifiers. It allows you to format and print values based on their type.

Example 1:fmt.Println()

package mainimport"fmt"funcmain() {fmt.Println("Hello, World!")fmt.Println("Hello, Sparta!")}

Output:

Hello, World!Hello, Sparta!

Example 2:fmt.Print()

package mainimport"fmt"funcmain() {fmt.Print("Hello ")fmt.Print("Sparta!")}

Output:

Hello Sparta!

Example 3:fmt.Printf()

package mainimport"fmt"funcmain() {fmt.Printf("%s\n","Hello, Sparta!")fmt.Printf("%d\n",12345)fmt.Printf("%g\n",12.50)fmt.Printf("%t\n",true)}

Output:

Hello, Sparta!1234512.50true

In the last example, we used format specifiers such as%s for strings,%d for integers,%g for floating-point numbers, and%t for booleans. The\n represents a new line character, which adds a line break after each print statement.

These print statements are essential for displaying output and debugging in Go, allowing you to communicate with the user and inspect the values of variables during program execution.

Go Format Specifiers

TypeFormat Specifier
Integer%d
Float%g
String%s
Boolean%t
Character%c
Hexadecimal%x
Scientific notation%e
Octal%o
Pointer%p
Width%*d

String in Go

  • A string in Go is asequence of bytes.
  • Strings areenclosed in double quotes ("like this") or backticks (`like this`).
  • Strings in Go areimmutable, meaning they cannot be changed once created.
  • Go provides arich set of string manipulation functions in thestrings package for tasks likesearching, replacing, splitting, and more.
  • Strings can becompared using the== or!= operators forequality or inequality.

String Methods

MethodDescriptionExample
Compare()Compares two strings lexicographically"abc".Compare("abd") // returns -1"
Contains()Returnstrue if a string contains another string"abcdef".Contains("cd") // returns true"
ToUpper()Converts a string to uppercase"hello world".ToUpper() // returns "HELLO WORLD"
ToLower()Converts a string to lowercase"Hello World".ToLower() // returns "hello world"
Replace()Replaces all occurrences of a substring with another substring"hello world".Replace("world", "everyone") // returns "hello everyone"
Split()Splits a string into an array of substrings based on a separator string"hello,world".Split(",") // returns ["hello", "world"]"
Join()Joins an array of substrings into a single string using a separator stringstrings.Join([]string{"hello", "world"}, ",") // returns "hello,world"

String Formatting

SpecifierDescriptionExample
%sFormats a stringfmt.Sprintf("Name: %s", name)
%dFormats an integerfmt.Sprintf("Age: %d", age)
%fFormats a floating-point numberfmt.Sprintf("Price: %.2f", price)
%tFormats a boolean valuefmt.Sprintf("Is available: %t", isAvailable)

Example Code

package mainimport ("fmt""strings")funcmain() {// Define a string variablemessage:="hello world"// Compare two stringsresult:=strings.Compare("abc","abd")fmt.Println(result)// Output: -1// Check if a string contains another stringresult=strings.Contains(message,"world")fmt.Println(result)// Output: true// Convert a string to uppercaseresult=strings.ToUpper(message)fmt.Println(result)// Output: HELLO WORLD// Convert a string to lowercaseresult=strings.ToLower(message)fmt.Println(result)// Output: hello world// Replace all occurrences of a substring with another substringresult=strings.Replace(message,"world","everyone",-1)fmt.Println(result)// Output: hello everyone// Split a string into an array of substringsresultArray:=strings.Split(message," ")fmt.Println(resultArray)// Output: [hello world]// Join an array of substrings into a single stringresult=strings.Join(resultArray,",")fmt.Println(result)// Output: hello,world}

Slice in Go

  • Aslice in Go is avariable-size sequence of elements that provides a moreflexible and powerful alternative to arrays.
  • Slices are builton top of arrays and provide adynamic view into the underlying array.
  • Unlike arrays, slices cangrow or shrink in size as needed, allowing for moreefficient memory usage.
  • Slices are represented by athree-part structure: apointer to the underlying array, alength indicating the number of elements in the slice, and acapacity representing the maximum number of elements the slice can hold.
  • Slices are widely used in Go to work withcollections of data, such as lists, buffers, or dynamic arrays.

Example: Working with Slices

package mainimport"fmt"funcmain() {// Create a slicenumbers:= []int{1,2,3,4,5}// Accessing elements of a slicefmt.Println(numbers[0])// Output: 1fmt.Println(numbers[2])// Output: 3// Modifying elements of a slicenumbers[1]=10fmt.Println(numbers)// Output: [1 10 3 4 5]// Slicing a sliceslice:=numbers[2:4]fmt.Println(slice)// Output: [3 4]}

Slice Methods

MethodDescriptionExample
append()Adds elements to a slice.slice = append(slice, 4, 5)
copy()Copies elements from one slice to another.copy(destination, source)
DeepEqual()Compares two slices for equality.isEqual := reflect.DeepEqual(slice1, slice2)
len()Returns the length of a slice.length := len(slice)

Go Array vs Slice

FeatureArraySlice
DefinitionFixed-size sequence of elementsVariable-size sequence of elements
Syntaxvar arr [size]Typevar slc []Type
LengthFixed, cannot changeCan change, dynamic
CapacitySame as lengthCan be larger than the length
Indexingarr[i]slc[i]
Creationarr := [3]int{1, 2, 3}slc := []int{1, 2, 3}
ResizingNot possiblePossible usingappend orcopy
Creating from an arrayN/Aarr[start:end]
Underlying structurePlain arrayReference to an array
Memory usageLess (in-place storage)More (reference + metadata)
  • When passing an array to a function, Go makes a copy of the array, and the function works on the copy. So, any modifications to the array inside the function do not affect the original array in the calling function.
  • On the other hand, when passing a slice to a function, Go passes a reference to the underlying array, which means that the function can modify the original array.

Here's an example demonstrating the differences:

package mainimport ("fmt")funcmodifyArray(arr [3]int) {arr[0]=100fmt.Println("Inside modifyArray:",arr)}funcmodifySlice(slc []int) {slc[0]=100fmt.Println("Inside modifySlice:",slc)}funcmain() {arr:= [3]int{1,2,3}slc:= []int{1,2,3}fmt.Println("Before modifyArray:",arr)modifyArray(arr)fmt.Println("After modifyArray:",arr)fmt.Println("\nBefore modifySlice:",slc)modifySlice(slc)fmt.Println("After modifySlice:",slc)}
OUTPUTBefore modifyArray: [1 2 3]Inside modifyArray: [100 2 3]After modifyArray: [1 2 3]Before modifySlice: [1 2 3]Inside modifySlice: [100 2 3]After modifySlice: [100 2 3]

In summary, when passing an array to a function, you're working with a copy, while when passing a slice, you're working with a reference to the original data. This is the primary difference when passing arrays and slices to functions in Go.

Go Map

Go maps are a built-in data structure that associate keys with values. They are similar to dictionaries in Python or hash tables in other programming languages. Some key features of Go maps include:

  • Dynamic size: Maps in Go can grow or shrink in size as needed.
  • Unordered: The order in which elements are stored in a map is not guaranteed, and iterating over a map may yield different orders.
  • Reference type: Maps are reference types, which means that when you assign a map to another variable, they both point to the same underlying data. Modifying one will affect the other.
  • Zero value: The zero value of a map isnil. Anil map has no keys, nor can keys be added.

Here's a summary of common map operations in Go:

  • Create a map: To create a map, you can use themake function or initialize it with key-value pairs.
  • Add/Update an entry: To add or update a key-value pair in the map, use the assignment operator (=).
  • Delete an entry: To remove a key-value pair from the map, use thedelete function.
  • Get an entry: To retrieve the value of a key in the map, use the index operator ([]).
  • Check if key exists: To verify if a key is in the map, use the, ok idiom when getting an entry.
  • Length of the map: To get the number of entries in the map, use thelen function.
  • Iterate over the map: To loop through the map's key-value pairs, use therange keyword in afor loop.
OperationDescriptionExample
Create a mapInitialize a new mapages := make(map[string]int)
Create a map with valuesInitialize a map with key-value pairsages := map[string]int{"John": 30, "Jane": 28}
Add an entryAdd a key-value pair to the mapages["Alice"] = 25
Update an entryUpdate the value of a key in the mapages["John"] = 31
Delete an entryRemove a key-value pair from the mapdelete(ages, "John")
Get an entryRetrieve the value of a key in the mapage := ages["John"]
Check if key existsVerify if a key is in the mapage, ok := ages["John"]; if ok { ... }
Length of the mapGet the number of entries in the mapcount := len(ages)
Iterate over the mapLoop through the map's key-value pairsfor key, value := range ages { ... }

Projects in the Repository

This repository also contains several projects that you can explore and use. Each project focuses on a different aspect of software development. Here is a list of the projects included along with a brief explanation:

  • blog_post_orm_system: A blog post management system with an ORM (Object-Relational Mapping) approach.
  • Updated migrations of blog_post_orm_system: Updated migrations for the blog post management system using ORM.
  • budget_management_system_orm: A budget management system implemented using an ORM approach.
  • education-management-system: A system for managing educational resources and information.
  • library_management_api: An API for managing library resources and operations.
  • simple_blog_api: A simple API for creating and managing blog posts.
  • task_management_api_graphql: An API for managing tasks using GraphQL.
  • task_manager_api: An API for managing tasks and tracking progress.
  • task_manager_api_with_bun: An API for task management using the Bun ORM.
  • task_tracker_api_with_graphql_and_bun: An API for tracking tasks using GraphQL and the Bun ORM.

Each project has its ownREADME file in its respective repository. You can navigate to each project's repository to find more information about the project, its purpose, and instructions on how to use it. Feel free to explore and utilize these projects according to your requirements.


[8]ページ先頭

©2009-2025 Movatter.jp