All Go Rust Python PHP JavaScript
Chrome Dev Summit to secure your spot in workshops, office hours and learning lounges!

How to Remove Duplicates in List in Python

In Python, there are 3 ways to remove duplicates in list. Using Built-in set Function The built-in set() function returns a new set object, optionally with elements taken from iterable. If you later need a real list again, you can similarly pass the set to the list() function. The following example should cover whatever you are trying to do: #!/usr/bin/python3 a = [1, 3, 1, 3, 2] b = list(set(a)) print(b) [1, 2, 3] As you can see from the example result, the original order is not maintained. As mentioned above, sets themselves are unordered collections, so the order is lost. Using OrderedDict.fromkeys Method Return an instance of a dict subclass that has methods specialized for rearranging dictionary order. If order is important to you, then you will have to use a different mechanism. A very common solution for this is to rely on OrderedDict to keep the order of keys during insertion: #!/usr/bin/python3 # Import module from collections import OrderedDict a = [1, 3, 1, 3, 2] b = list(OrderedDict.fromkeys(a)) print(b) [1, 3, 2] Using dict.fromkeys Method Starting with Python 3.7, the built-in dictionary is guaranteed to maintain the insertion order as well: #!/usr/bin/python3 a = [1, 3, 1, 3, 2] # Python 3.7+ b = list(dict.fromkeys(a)) print(b) [1, 3, 2]
pooriabt

How to Create Multiline Comments in Python

In Python, using the triple-quoted strings is the easiest way to create multiline comments. Using triple-quoted Strings String literals can span multiple lines. One way is using triple-quotes: """...""" or '''...'''. You can use triple-quoted strings. When they're not a docstring, they are ignored. See the following example: #!/usr/bin/python3 ''' This is a multiline comment. ''' """" This is a multiline comment. """ def parses(token): """ This function parses a token. TODO: write a decent docstring :-) """ pass Make sure to indent the leading ''' appropriately to avoid an IndentationError. Using Consecutive Single-Line Comments Python's style guide, PEP8, favors using consecutive single-line comments, like this: #!/usr/bin/python3 # This is a multiline # comment. Python Errors IndentationError: unexpected indent #!/usr/bin/python3 '''... ''' IndentationError: unexpected indent
aweis

How to Execute a Shell Command in Go

In Golang, using the exec.Command() function is the easiest way to execute a shell command Using exec.Command Function Command returns the Cmd struct to execute the named program with the given arguments. You can execute a shell command using the exec.Command() function. For example, package main import ( "bytes" "fmt" "os/exec" ) func main() { cmd := exec.Command("ls", "-lh") var out bytes.Buffer cmd.Stdout = &out err := cmd.Run() if err != nil { // log.Fatal(err) } fmt.Println(out.String()) } total 188K -rw-r--r--...
aweis

How to Get File Length in Go

In Golang, there are 2 ways to get file length. Using file.Stat Function Open opens the named file for reading. If successful, methods on the returned file can be used for reading; the associated file descriptor has mode O_RDONLY. See the following example: package main import ( "fmt" "os" ) func main() { f, err := os.Open("access.log") if err != nil { // log.Fatal(err) } defer f.Close() stat, _ := f.Stat() fmt.Println(stat.Size()) // fmt.Println(FormatByteSI(stat.Size())) } 2626 2.6 kB Using os.Stat Function If you don't want to open the file, you can directly call os.Stat instead. For example, package main import ( "fmt" "os" ) func main() { stat, err := os.Stat("access.log") if err != nil { // log.Fatal(err) } fmt.Println(stat.Size()) // fmt.Println(FormatByteSI(stat.Size())) } 2626 2.6 kB
ada

How to Do a Case Insensitive Regular Expression in Go

In Golang, using the a case-insensitive flag is the easiest way to do a case insensitive regular expression. Using a case-insensitive flag You can set a case-insensitive flag as the first item in the regex. You can add a (?i) at the beginning of the pattern to make it case insensitive. See the following example: package main import ( "fmt" "regexp" ) func main() { s := "aBcd" r := regexp.MustCompile(`bc`) fmt.Println(r.Match([]byte(s))) r = regexp.MustCompile(`(?i)bc`) fmt.Println(r.FindString(s)) } false Bc For more information about flags, go through https://github.com/google/re2/wiki/Syntax.
ada

How to Access Command-Line Arguments in Go

In Golang, there are 2 ways to access command-line arguments passed to a program. Using os.Args Variable You can access the command-line arguments using the os.Args variable. Note that the first value in this slice is the path to the program, and os.Args[1:] holds the arguments to the program. For example, package main import ( "fmt" "os" ) // Command-Line Arguments // go run main.go -path=/home func main() { fmt.Println(os.Args[0]) fmt.Println(os.Args[1]) } ./main --path=/home Using flag Package Package flag implements command-line flag parsing. Go provides a `flag` package supporting basic command-line flag parsing. We'll use this package to implement our example command-line program. See the following example: package main import ( "flag" "fmt" ) // Command-Line Arguments // go run main.go -path=/home -n=10 -svar=ss func main() { pathPtr := flag.String("path", "tmp", "Path") nPtr := flag.Int("n", 42, "an int") var svar string flag.StringVar(&svar, "svar", "bar", "a string var") flag.Parse() fmt.Println(*pathPtr) fmt.Println(*nPtr) fmt.Println(svar) fmt.Println(flag.Args()) } /home 10 ss []
Unused

How to Count the Items in the Map in Go

In Golang, using the len function is the easiest way to count the items in the map structure. Using len Function The built-in function len take arguments of various types and return a result of type int. The implementation guarantees that the result always fits into an int. See the following example: package main import "fmt" func main() { m := make(map[string]int, 30) var n map[string]int fmt.Println(len(m)) fmt.Println(len(n)) } 0 0 len(s): string type string length in bytes [n]T, *[n]T array length (== n) []T slice length map[K]T map length (number of defined keys) chan T number of elements queued in channel buffer type parameter see below
Sambhav Khandelwal

How to Append Text to a File in Go

In Golang, using the os.O_APPEND flag is the easiest way to append text to a file Using os.OpenFile Function OpenFile is the generalized open call; most users will use Open or Create instead. It opens the named file with specified flag (O_RDONLY etc.). If the file does not exist, and the O_CREATE flag is passed, it is created with mode perm (before umask). If successful, methods on the returned File can be used for I/O. See the following example: package main import "os" func main() { // If the file doesn't exist, create it, or append to the file f, err := os.OpenFile("access.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) if err != nil { // log.Fatal(err) } defer f.Close() if _, err := f.Write([]byte("appended ...\n")); err != nil { // log.Fatal(err) } } appended ... appended ... If the file doesn't exist, create it, or append to the file. Constants: const ( // Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must be specified. O_RDONLY int = syscall.O_RDONLY // open the file read-only. O_WRONLY int = syscall.O_WRONLY // open the file write-only. O_RDWR int = syscall.O_RDWR // open the file read-write. // The remaining values may be or'ed in to control behavior. O_APPEND int = syscall.O_APPEND // append data to the file when writing. O_CREATE int = syscall.O_CREAT // create a new file if none exists. O_EXCL int = syscall.O_EXCL // used with O_CREATE, file must not exist. O_SYNC int = syscall.O_SYNC // open for synchronous I/O. O_TRUNC int = syscall.O_TRUNC // truncate regular writable file when opened. )
ada

How to Get the Name of a Function in Go

In Golang, using the runtime.FuncForPC function is the easiest way to get the name of a function Using runtime.FuncForPC Function The runtime.FuncForPC() function returns a *Func describing the function that contains the given program counter address, or else nil. See the following example: package main import ( "fmt" "runtime" ) func Debug() { if counter, _, _, ok := runtime.Caller(1); ok { name := runtime.FuncForPC(counter).Name() fmt.Println(name) } } func main() { Debug() } main.main
Unused

How to Iterate Over a Slice in Reverse in Go

In Golang, there are 2 ways to iterate over a slice in reverse. Using For Loop There is no convenient operator for this to add to the range one in place. You'll have to do a normal for loop counting down. See the following example: package main import ( "fmt" ) func main() { s := []string{"a", "b", "c", "d"} for i := len(s) - 1; i >= 0; i-- { fmt.Println(s[i]) } } d c b a Using For Range You can also do: package main import ( "fmt" ) func main() { s := []string{"a", "b", "c", "d"} l := len(s) for i := range s { fmt.Println(s[l-1-i]) } } d c b a
Patcher56

How to Check for NaN Values in Python

In Python, there are 2 ways to check for NaN values. Using math.isnan Method The math.isnan(x) method returns True if x is a NaN (not a number), and False otherwise. For example, #!/usr/bin/python3 # Import module import math f = float('nan') print(math.isnan(f)) True Using NaN Implement A NaN implemented following the standard, is the only value for which the inequality comparison with itself should return True: #!/usr/bin/python3 def isNaN(n): return n != n f = float('nan') print(isNaN(f)) True
ada

How to Check the Version of the Interpreter in Python

In Python, there are 3 ways to check what version of the Interpreter is interpreting my script. Using sys.version String A string containing the version number of the Python interpreter plus additional information on the build number and compiler used. For example, #!/usr/bin/python3 # Import module import sys print(sys.version) 3.10.4 (main, Apr 26 2022, 18:08:47) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] Using sys.version_info Tuple A tuple containing the five components of the version number: major, minor, micro, releaselevel, and serial. For example, #!/usr/bin/python3 # Import module import sys print(sys.version_info) if sys.version_info >= (3, 9): pass sys.version_info(major=3, minor=10, micro=4, releaselevel='final', serial=0) Using sys.hexversion Number The version number encoded as a single integer. For example, #!/usr/bin/python3 # Import module import sys print(sys.hexversion) 50988272
ada

How to Check If a Directory Exists in Python

In Python, there are 3 ways to check if a directory exists. Using os.path.isdir Method You can use os.path.isdir() to check if a directory exists, it really simple. For example, #!/usr/bin/python3 # Import module import os d = "./folder" print(os.path.isdir(d)) True Using os.path.exists Method The os.path.exists() method returns True if path refers to an existing path or an open file descriptor. For both files and directories: #!/usr/bin/python3 # Import module import os f = "./folder/file.txt" print(os.path.exists(f)) d = "./folder" print(os.path.exists(d)) True True Using pathlib Module You can use pathlib: #!/usr/bin/python3 # Import module import pathlib d = "./folder" print(pathlib.Path(d).is_dir()) True
aweis

How to Get the Filename Without the Extension from a Path in Python

In Python, there are 2 ways to get the filename without the extension from a path. Using pathlib Module You can use .stem from pathlib to get the filename without the extension from a path, it really simple. For example, #!/usr/bin/python3 # Import module import pathlib f = "/root/file.txt" print(pathlib.Path(f).stem) f = "/root/file.tar.gz" print(pathlib.Path(f).stem) file file.tar Note that if your file has multiple extensions .stem will only remove the last extension. Using splitext Method The os.path.splitext() method splits the pathname path into a pair (root, ext) such that root + ext == path, and the extension, ext, is empty or begins with a period and contains at most one period. See the following example: #!/usr/bin/python3 # Import module import os f = "/root/file.txt" print(os.path.splitext(f)[0]) /root/file Try this: #!/usr/bin/python3 # Import module import os def filename(f): base = os.path.basename(f) return os.path.splitext(base)[0] f = "/root/file.txt" print(filename(f)) file
Sambhav Khandelwal

How to Reverse a String in Python

In Python, there are 3 ways to reverse a string. Using slicing Slice notation takes the form [start:stop:step]. #!/usr/bin/python3 s = "Hello World" print(s[::-1]) # syntax # a[start:stop] # items start through stop-1 # a[start:] # items start through the rest of the array # a[:stop] # items from the beginning through stop-1 # a[:] # a copy of the whole array dlroW olleH Using reversed Function The reversed() built-in function returns a reverse iterator. For example, #!/usr/bin/python3 s = "Hello World" r = ''.join(reversed(s)) print(r) dlroW olleH Using recursion You can use recursion to reverse a string. The following example: #!/usr/bin/python3 def reverse(s): if len(s) == 1: return s return s[-1] + reverse(s[:-1]) s = "Hello World" print(reverse(s)) dlroW olleH if the string is decent length you'll run into RecursionError. Python Errors maximum recursion depth exceeded while calling a Python object: print(reverse("abcdef"*1000)) RecursionError: maximum recursion depth exceeded while calling a Python object
pooriabt

How to Prettyprint a JSON File in Python

In Python, there are 2 ways to prettyprint a JSON file. Using json module The json module already implements some basic pretty printing in the dump and dumps functions, with the indent parameter that specifies how many spaces to indent by: #!/usr/bin/python3 # Import module import json j = '[{"name":"foo", "age":10}]' parsed = json.loads(j) pretty = json.dumps(parsed, indent=2, sort_keys=True) print(pretty) [ { "age": 10, "name": "foo" } ] Using Command Line You can do this on the command line: pretty printing python3 -m json.tool some.json echo '[{"name":"foo", "age":10}]' | python3 -m json.tool [ { "name": "foo", "age": 10 } ]
Patcher56

How to Check If an Object Is of a Given Type in Python

In Python, there are 2 ways to check if an object is of a given type. Using isinstance Method The isinstance(object, classinfo) method returns True if the object argument is an instance of the classinfo argument, or of a (direct, indirect, or virtual) subclass thereof. Use isinstance to check if o is an instance of str or any subclass of str: #!/usr/bin/python3 o = "Hello" print(isinstance(o, str)) True If classinfo is not a type or tuple of types and such tuples, a TypeError exception is raised. Using type Method To check if the type of o is exactly str, excluding subclasses of str: #!/usr/bin/python3 o = "Hello" if type(o) is str: print("string") # Another alternative to the above: if issubclass(type(o), str): print("subclass") string subclass List of classinfo Types list of strings: #!/usr/bin/python3 print([t.__name__ for t in __builtins__.__dict__.values() if isinstance(t, type)]) [ 'BuiltinImporter', 'bool', 'memoryview', 'bytearray', 'bytes', 'classmethod', 'complex', 'dict', 'enumerate', 'filter', 'float', 'frozenset', 'property', 'int', 'list', 'map', 'object', 'range', 'reversed', 'set', 'slice', 'staticmethod', 'str', 'super', 'tuple', 'type', 'zip', 'BaseException', 'Exception', 'TypeError', 'StopAsyncIteration', 'StopIteration', 'GeneratorExit', 'SystemExit', 'KeyboardInterrupt', 'ImportError', 'ModuleNotFoundError', 'OSError', 'OSError', 'OSError', 'EOFError', 'RuntimeError', 'RecursionError', 'NotImplementedError', 'NameError', 'UnboundLocalError', 'AttributeError', 'SyntaxError', 'IndentationError', 'TabError', 'LookupError', 'IndexError', 'KeyError', 'ValueError', 'UnicodeError', 'UnicodeEncodeError', 'UnicodeDecodeError', 'UnicodeTranslateError', 'AssertionError', 'ArithmeticError', 'FloatingPointError', 'OverflowError', 'ZeroDivisionError', 'SystemError', 'ReferenceError', 'MemoryError', 'BufferError', 'Warning', 'UserWarning', 'EncodingWarning', 'DeprecationWarning', 'PendingDeprecationWarning', 'SyntaxWarning', 'RuntimeWarning', 'FutureWarning', 'ImportWarning', 'UnicodeWarning', 'BytesWarning', 'ResourceWarning', 'ConnectionError', 'BlockingIOError', 'BrokenPipeError', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionRefusedError', 'ConnectionResetError', 'FileExistsError', 'FileNotFoundError', 'IsADirectoryError', 'NotADirectoryError', 'InterruptedError', 'PermissionError', 'ProcessLookupError', 'TimeoutError' ]
Unused

How to Check Whether a Path Exists in Rust

In Rust, using the Path::exists function is the easiest way to check whether a path exists. Using Path::exists Function The Path::exists() function returns true if the path points at an existing entity. See the following example: // Rust 1.5+ use std::path::Path; fn main() { let b = Path::new("file.txt").exists(); println!("{}", b); } true If you want to check errors, call fs::metadata: use std::fs; fn main() -> std::io::Result { let metadata = fs::metadata("file.txt")?; println!("{:?}", metadata.file_type()); Ok(()) } FileType(FileType { mode: 33252 })
aweis

How to Find the Index of an Element in a Vector in Rust

In Rust, using the position function is the easiest way to find the index of an element in a vector. Using position Method The position() method searches for an element in an iterator, returning its index. position() is short-circuiting; in other words, it will stop processing as soon as it finds a true. See the following example: fn main() { let a = ["a", "b", "c"]; let i = a.iter().position(|&x| x == "b"); println!("{:?}", i); // None let i = a.iter().position(|&x| x == "d"); println!("{:?}", i); } Some(1) None Stopping at the first true: fn main() { let a = [1, 2, 3, 4]; let i = a.iter().position(|&x| x >= 2); println!("{:?}", i); } Some(1)
pooriabt

How to Convert a Str to a &[u8] in Rust

In Rust, there are 2 ways to convert a str to a &[u8]. Using as_bytes Function The as_bytes() method converts a string slice to a byte slice. To convert the byte slice back into a string slice, use the from_utf8 function. See the following example: fn main() { let s = "abc"; let b = s.as_bytes(); println!("{:?}", b); } [97, 98, 99] Using a Byte Literal You can use a byte literal. For example, fn main() { let b = b"abc"; println!("{:?}", b); } [97, 98, 99] Rust Errors non-ASCII character in byte constant: let b = b"a̐bc"; error: non-ASCII character in byte constant --> src/main.rs:2:14 | 2 | let b = b"a̐bc"; | ^ byte constant must be ASCII but is '\u{310}' | help: if you meant to use the UTF-8 encoding of '\u{310}', use \xHH escapes | 2 | let b = b"a\xCC\x90bc";
aweis

How to Index a String in Rust

In Rust, there are 2 ways to index a string. Using as_bytes Function If the enum is C-like, then you can create a static array of each of the variants and return an iterator of references to them: fn main() { let s = "abc"; let b: u8 = s.as_bytes()[1]; let c: char = b as char; println!("{}", c); } b Using chars Iterator The str.chars() method returns an iterator over the [`char`]s of a string slice. fn main() { let s = "abc"; let c = s.chars().nth(1).unwrap(); println!("{}", c); } b
pooriabt

How to Iterate through the Values of an Enum in Rust

In Rust, there are 2 ways to iterate through the values of an enum. Using a static array If the enum is C-like, then you can create a static array of each of the variants and return an iterator of references to them: use self::Direction::*; use std::slice::Iter; #[derive(Debug)] pub enum Direction { North, South, East, West, } impl Direction { pub fn iterator() -> Iter { static DIRECTIONS: [Direction; 4] = [North, South, East, West]; DIRECTIONS.iter() } } fn main() { for direction in Direction::iterator() { println!("{:?}", direction); } } North South East West Using strum Crate Install Add the following line to your Cargo.toml file: [dependencies] strum = "0.24" strum_macros = "0.24" # You can also use the "derive" feature, and import the macros directly from "strum" # strum = { version = "0.24", features = ["derive"] } Strum Usage Strum is a set of macros and traits for working with enums and strings easier in Rust. // You need to bring the trait into scope to use it! use strum::IntoEnumIterator; use strum_macros::EnumIter; #[derive(Debug, EnumIter)] pub enum Direction { North, South, East, West, } fn main() { for direction in Direction::iter() { println!("{:?}", direction); } } North South East West
pooriabt

How to Create Nested Directories in Go

In Golang, using the os.MkdirAll function is the easiest way to create nested directories Using os.MkdirAll Function The os.MkdirAll() function creates a directory named path, along with any necessary parents, and returns nil, or else returns an error. See the following example: package main import ( "os" ) func main() { if err := os.MkdirAll("path/subdir", 0750); err != nil && !os.IsExist(err) { // panic() } // create file } path/subdir If path is already a directory, MkdirAll does nothing and returns nil.
Sambhav Khandelwal

How to Download a Large File in Go

In Golang, using the io.copy function is the easiest way to download a large file Using io.Copy Function The io.Copy() function copies from src to dst until either EOF is reached on src or an error occurs. It returns the number of bytes copied and the first error encountered while copying, if any. For example, package main import ( "errors" "io" "net/http" "os" ) func downloadFile(path, url string) error { f, err := os.Create(path) if err != nil { return err } defer f.Close() resp, err := http.Get(url) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return errors.New("error") } _, err = io.Copy(f, resp.Body) if err != nil { return err } return nil } func main() { downloadFile("./go.tar.gz", "https://go.dev/dl/go1.18.1.src.tar.gz") }
ada

How to Convert a Bool to a String in Go

In Golang, there are 2 ways to convert a bool to a string. Using strconv.FormatBool Function The strconv.FormatBool() function returns "true" or "false" according to the value of b. For example, package main import ( "fmt" "strconv" ) func main() { b := true s := strconv.FormatBool(b) fmt.Printf("%q\n", s) } "true" Using fmt.Sprintf Function The fmt.Sprintf() function formats according to a format specifier and returns the resulting string. You can use fmt.Sprintf() with the "%t" or "%v" formatters. See the following example: package main import ( "fmt" ) func main() { b := true s := fmt.Sprintf("%t", b) fmt.Printf("%q\n", s) s = fmt.Sprintf("%v", b) fmt.Printf("%q\n", s) } "true" "true"
Tomoki

How to Index Characters in a String in Go

In Golang, there are 2 ways to index characters in a string. Using individual characters In UTF-8, ASCII characters are single-byte corresponding to the first 128 Unicode characters. Strings behave like slices of bytes. A rune is an integer value identifying a Unicode code point. For example, package main import "fmt" func main() { s := "Hello,世界" fmt.Println(string(s[1])) fmt.Println(string([]rune(s)[6])) } e 世 Using strings.Split Function Split slices s into all substrings separated by sep and returns a slice of the substrings between those separators. See the following example: package main import ( "fmt" "strings" ) func main() { s := "Hello,世界" b := strings.Split(s, "") fmt.Println(b[6]) } 世 Golang Errors panic: runtime error: index out of range [9] with length 8: fmt.Println(b[9]) panic: runtime error: index out of range [9] with length 8 goroutine 1 [running]:
Patcher56

How to Unpack Array as Arguments in Go

In Golang, there are 2 ways to unpack array as arguments. Using Variadic Functions Variadic functions can be called with any number of trailing arguments. Here’s a function that will take an arbitrary number of ints as arguments. For example, package main import "fmt" // Variadic Functions func sum(args ...int) int { total := 0 for _, v := range args { total += v } return total } func main() { a := []int{1, 2, 3} t := sum(a...) fmt.Println(t) t = sum(2, 3, 4) fmt.Println(t) } 6 9 Using Reflection If you really want to do this dynamically on a function of fixed number of arguments, you can use reflection: package main import ( "fmt" "reflect" ) func sum(a, b, c int) int { return a + b + c } func main() { a := []int{1, 2, 3} var args []reflect.Value for _, v := range a { args = append(args, reflect.ValueOf(v)) } fun := reflect.ValueOf(sum) result := fun.Call(args) sum := result[0].Interface().(int) fmt.Println(sum) } 6
Unused

How to Set Timeout for http.Get Requests in Go

In Golang, there are 2 ways to set timeout for http.Get requests Using http.Client.Timeout Field Timeout specifies a time limit for requests made by this Client. The timeout includes connection time, any redirects, and reading the response body. See the following example: package main import ( "fmt" "net/http" "time" ) func main() { client := http.Client{ Timeout: 2 * time.Second, } resp, err := client.Get("https://google.com") fmt.Println(resp, err) } context deadline exceeded (Client.Timeout exceeded while awaiting headers) Using context.WithTimeout Function If you want to do it per request, err handling ignored for brevity: package main import ( "context" "fmt" "net/http" "time" ) func main() { ctx, cncl := context.WithTimeout(context.Background(), 3*time.Second) defer cncl() req, _ := http.NewRequestWithContext(ctx, http.MethodGet, "https://google.com", nil) resp, err := http.DefaultClient.Do(req) fmt.Println(resp, err) } context deadline exceeded
Tomoki

How to Subtracting time.Duration from Time in Go

In Golang, using the time.Duration function is the easiest way to subtract time from a time.Time Using time.Duration Function A Duration represents the elapsed time between two instants as an int64 nanosecond count. The representation limits the largest representable duration to approximately 290 years. For example, package main import ( "fmt" "time" ) func main() { now := time.Now() m := 10 t := now.Add(time.Duration(m) * time.Minute) fmt.Println(now.Format(time.ANSIC)) fmt.Println(t.Format(time.ANSIC)) t = now.Add(-10 * time.Second) fmt.Println(t.Format(time.ANSIC)) } Tue May 3 11:00:55 2022 Tue May 3 11:10:55 2022 Tue May 3 11:00:45 2022 Using time.ParseDuration Function ParseDuration parses a duration string. When you need to substract an hour and a half, you can do that like so: package main import ( "fmt" "time" ) func main() { now := time.Now() duration, _ := time.ParseDuration("-1.5h") t := now.Add(duration) fmt.Println(now.Format(time.ANSIC)) fmt.Println(t.Format(time.ANSIC)) // hours, _ := time.ParseDuration("10h") // complex, _ := time.ParseDuration("1h10m10s") // micro, _ := time.ParseDuration("1µs") // The package also accepts the incorrect but common prefix u for micro. // micro2, _ := time.ParseDuration("1us") } Tue May 3 11:04:54 2022 Tue May 3 09:34:54 2022
Tomoki

How to Convert an Integer to a Float Number in Go

In Golang, using the float64 function is the easiest way to convert an integer to a float number. Using float64 Function The easiest way to convert an integer to a float number in Golang: package main import "fmt" func main() { i := 6 f := float64(i) fmt.Printf("%T: %f\n", f, f) fmt.Printf("%T: %.3f\n", f, f) f32 := float32(i) fmt.Printf("%T: %f\n", f32, f32) } float64: 6.000000 float64: 6.000 float32: 6.000000 Proper parentheses placement is key: For example, package main import "fmt" func main() { i := 1234 f := float64(i) / 10.0 fmt.Printf("%T: %f\n", f, f) // wrong f = float64(i / 10.0) fmt.Printf("%T: %f\n", f, f) } float64: 123.400000 float64: 123.000000
Patcher56