Golang Getting Started Series 4: How to Understand the Interface

I talked a lot about the basics of the Go language, including the installation of the go environment, the syntax of the go language, etc. If you are interested, you can first look at the previous article. http://quickintro123.com/index.php/category/golang/

Today I officially started writing Go code, and talked about how to understand the interface .

1. What is the interface

interface is one of the basic characteristics of the GO language. Can be understood as a type of specification or convention. It is not the same as Java or C #. It does not need to show that it implements an interface. It does not have inheritance or subclasses or the "implements" keyword. It just implements the methods in the interface implicitly by convention. Therefore, interfaces in Golang make coding more flexible and extensible.

How to understand the interface in go language? Just remember the following three points:

  1. interface is a collection of method declarations
  2. Any type of object implements all the methods declared in the interface , it means that the type implements the interface.
  3. interface can be used as a data type. Any object that implements the interface can assign a value to the corresponding interface type variable.

Note:

a. Interface can be implemented by any object, and a type / object can also implement multiple interfaces
b. Methods cannot be overloaded, such as eat () eat (s string) cannot exist at the same time

2. Interface implementation

package main

import "fmt"

type Phone interface {
    call()
}

type NokiaPhone struct {
}

func (nokiaPhone NokiaPhone) call() {
    fmt.Println("I am Nokia, I can call you!")
}

type ApplePhone struct {
}

func (iPhone ApplePhone) call() {
    fmt.Println("I am Apple Phone, I can call you!")
}

func main() {
    var phone Phone
    phone = new(NokiaPhone)
    phone.call()

    phone = new(ApplePhone)
    phone.call()
}

3. interface query

If interface A implements all methods in interface B, then A can be converted to interface B.

 if varName2, ok := varName1.(interface2|typeName); ok {
    // At this time, the type of varName2 is changed from interface1 to interface2, or varName1 is not a variable of typeName
  } else {
    // Cannot convert interface, or varName1 is not a variable of typeName

4. The interface {} type

The interface {} type does not declare any method, commonly known as an empty interface. interface {} is very useful when we need to store any type of value, a bit similar to the C language void * type.

package main

import (
    "fmt"
)

func PrintAll(vals []interface{}) {
    for _, val := range vals {
        fmt.Println(val)
    }
}

func main() {
    names := []string{"stanley", "david", "oscar"}
    vals := make([]interface{}, len(names))
    for i, v := range names {
        vals[i] = v
    }
    PrintAll(vals)
}

Note, however, that [] T cannot be directly assigned to [] interface {}

t := []int{1, 2, 3, 4}

var s [] interface {} = t 

The following error is output when compiling:

cannot use t (type [] int) as type [] interface {} in assignment

Finally

I made a brief introduction to the interface features in Go. I think for Go language, the most exquisite design should be the interface. If you are interested, you can study it.

Posted in golang | Tagged , , | 2 Comments

Golang Getting Started Series 3: Go Language Basics Summary

I have already introduced the configuration of the Go language and the pits that are easy to encounter when I first learn Go. You can check the previous article http://quickintro123.com/index.php/tag/golang/

In this article, the following is a basic knowledge of Go language for beginners:

1. The basic structure of the Go program

The following is the basic structure of a Go program, including (package declarations, import packages, functions, etc.)

Package main // Define the package name, package main represents a program that can be executed independently, and each Go application contains a package named main.

Import "fmt" // Import the package (function, or other element) you need to use

Func main() { // The entry function of the program. The main function is required for every executable program, and is generally the first function to be executed after startup.
    fmt.Println("Hello, World!")
}

2. Data type

Go built-in basic data types include basic data types and advanced data types

(1) Basic data type
* Boolean type (bool)

Numerical type
* Integer type (byte, int/uint, int8/uint8, int16/uint16, int32/uint32, int64/uint64)
* Floating point type (float32, float64)
* Plural type (complex64, complex128)

String type
* Go strings are concatenated by a single byte. Identify Unicode text using UTF-8 encoding.

(2) Advanced data types

  • Array
  • Slice
  • Dictionary (map)
  • Channel
  • Function
  • Structure
  • Interface
  • Pointer (*Xxx, Pointer, uintptr)

If divided according to the underlying data structure, the value type includes (all basic data types, arrays, structures), and the reference types include (slice, map, channel, function, interface, pointer)

3. Variables & Constants

(1) Variable names consist of letters, numbers, and underscores, where the first letter cannot be a number, for example: var name string

(2) Declaration
a. Specify the variable type. If you do not assign a value after the declaration, use the default value.

Var name string
Name = "Jack"

b. Determine the type of the variable according to the value.

Var name = "Jack"

c. Short form, omitting var, note

Age := 10

Attention
(:=) is the preferred form of using variables
(:=) can only be used in function bodies, not in the declaration and assignment of global variables.
(:=) The variable on the left should not be declared, otherwise it will cause a compilation error.

(3) The data type of a constant can only be boolean, numeric (integer, float, and complex) and string.
a. Constant declaration: const b string = "abc"
b. iota, special constant

const (
    a = iota
    b
    c
)
  • represents a continuous, untyped integer constant,
  • Constant declaration statements starting with const,
  • Starting from 0, incrementing once without assigning a constant
  • Once the constant declaration statement starting with const is returned to 0

4. Operator

(1) Arithmetic operator, a + b, including (+,-,*, /,%,++,--)
(2) Relational operators, return True or False, a == b , including (==,!=,>,<,>=,<=)
(3) Logical operators, return True or False, including (&&,||,!)
(4) Address operator

& : Return variable storage address (&originalValue)

  • : pointer variable (*pointerValue)

(5) Receive operator for receiving channel data or adding data to the channel (intChan<-1, <-intChan)

5. Error handling

(1) error interface, (errors.New(value), fmt.Error(), custom error type)

func Divide(a, b float64) (result float64, err error) {
    if b == 0 {
        result = 0.0
        err = errors.New("runtime error: divide by zero")
        return
    } else {
        result = a / b
        err = nil
    }
    return
}

(2) panic function, panic(value) is used in conjunction with the error interface.

var user = os.Getenv("USER")
    if user == "" {
        panic("The USER environment variable is not set.")
    }

(3)The recover function, combined with the defer statement,

func TestB() (err error) {
    defer func() { //Set recovery when an exception occurs
        if x := recover(); x != nil {
            err = fmt.Errorf("internal error: %v", x)
        }
    }()

    panic("func TestB(): panic")
}

6. Go basic commands

The go build command is mainly used for test compilation. During the compilation of the package, the packages associated with it are compiled at the same time if necessary.

Go build hello.go

The go get command is mainly used to dynamically obtain remote code packages.

Go get github.com/go-sql-driver/mysql

The go run command is mainly used to compile and run the Go program.

Go run hello.go

The go test command will automatically read the file named *_test.go under the source directory to generate and run the executable file for testing.

Posted in golang | Tagged , | 3,756 Comments

Golang Getting Started Series 2: Learning the pits that the Go language needs to pay attention to

In the previous chapter, we have already seen the configuration of the Go environment. If you don't understand, please check the previous article go Environment construction , in this chapter we will learn the points to note in the basic syntax of the Go language.

GO language basic grammar

The basic syntax of go, I will not go into detail here, you can view this article, learn the detailed syntax of Go: https://golang.org/doc/

It is best to try the above examples, one by one, this works best.

The following is the basic structure of a Go program, including (package declarations, import packages, functions, etc.)

package main   // Define the package name, package main represents a program that can be executed independently, and each Go application contains a package named main.

import "fmt"   // Import the package (function, or other element) you need to use

func main() {  // The entry function of the program. The main function is required for every executable program, and is generally the first function to be executed after startup.
   fmt.Println("Hello, World!")
}

GO language attention pit

No matter what you learn, you will encounter a variety of pits at the beginning. Here is a summary of the various pits encountered in the process of learning the go language.

  1. Anyone who writes C# will have a separate line of "{", but this is wrong in go. "{" must be on the same line as the method body. The first time I wrote go, I made this mistake and I don't know where the error is.
Func main() {
   fmt.Println("Hello, World!")
}
  1. else in the if...else statement must be on the same line as if ' } ', otherwise compilation error
 Var a int = 30

 If a < 20 {
    fmt.Print("a<20")
 } else {
    fmt.Print("a>=20")
 }
  1. The definition of the package name. You must declare the package name in the first line of the non-comment in the source file, such as: package main. Package main represents a program that can be executed independently, and each Go application contains a package called main.
Package main
  1. In the Go program, a line represents the end of a statement. Each statement does not need to end with a semicolon like other languages ​​in the C family, as these tasks are done automatically by the Go compiler.

If you plan to write multiple statements on the same line, you must use ; artificial distinction, but we do not encourage this practice in actual development.

fmt.Println("Hello, World!")
fmt.Println("www.fpeach.com")
  1. The main() function is required for every executable program, and is generally the first function to be executed after startup. However, there can only be one main() function in each package, otherwise it will report a main redeclared in this block previous declaration at .. error.
Package main

Import "fmt"

Func main() {
   /* This is my first simple program */
   fmt.Println("Hello, World!")
}
  1. When functions, structures, etc., begin with an uppercase letter, such as GetInfo, objects that use this form of identifier can be used by the code of the outer package. This is called exporting (like in object-oriented languages). Public); identifiers that begin with a lowercase letter are invisible to the outside of the package, but they are visible and usable throughout the package (like protected in an object-oriented language).
// public function, can be used by the code of the external package
Func Test() {
   .
   .
   .
}

// private function, the inside of the package is visible,
Func test2() {
   .
   .
   .
}
  1. Identifiers are used to name program entities such as variables and types. An identifier is actually a sequence of one or more letters (A~Z and a~z) numbers (0~9) and underscores, but the first character must be a letter or an underscore and cannot be a number.

The following are invalid identifiers:

1ab (starting with a number)
Case (key in Go language)
a+b (operator is not allowed)
  1. Error no new variables on left side of := , meaning, "There is no new variable on the left!"
Func main() {
    Var b int = 20
    b := 30
    fmt.Print(b)
}

The solution is: for the form x, y:=...., just name one of the variables as new.

  1. You cannot use ++ auto increment or - - self-decreasing operator to initialize variables and assign values to variables
Package main

Import "fmt"

Func main(){
    Var a int = 10
    Var b int = a++

    Var c int = 20
    c = a++

    fmt.Print(a, b, c)
}
Posted in golang, Uncategorized | Tagged , , | 784 Comments

Inspiring sentences about self-confidence

Confident people bring their own aura. Here are some of the sentences I have collected about self-confidence. They are very inspirational and can make us feel confident and beautiful.

  • Where does freedom come from? From self-confidence, self-confidence comes from self-discipline.

  • Courage should not be supported by the boundless mana, but in front of the people you care about, the kind of momentum that is unprecedented. This kind of momentum is not the self-confidence that knows what it can do, but the pride that knows its inaction. - This is the heart of the strong, but also the heart of the hero.

  • People who are claws and claws are often fragile. Because a truly powerful person is self-confident, self-confidence will be mild, and gentleness will be firm.

  • Be a little handsome, calm, natural, true, and happy. You will be more confident and happier.

  • The day will be reduced to the people of the S, also must first bitter their minds, labor and muscles, hungry their body, empty body, do what they do, so they are willing to endure and gain what they can't.

  • The gains you get will greatly enhance your self-confidence, and self-confidence will increase your courage.

  • Confidence in the face, goodness in the bottom of my heart, the bones in the blood, and the strength in my life.

I hope that these sentences will make reading friends more confident and calm.

Posted in learning | Tagged | 1,092 Comments

Inspirational sentence about hard work

Struggling life is a happy life. As we strive to move toward the goal, our hearts will be full of joy. Here are some of the inspirational sentences I've collected about hard work. It makes people feel excited when they read it.

All efforts are worthy of expectation, and every dream should be irrigated!

Skills are things that can be learned as long as you study hard and practice hard.

Talent determines the upper limit and strives to determine the lower limit. The level of effort of most people does not reach the level of talent.

Don't give up at all times, you can try your best to do your best before the last minute.

You have to work hard enough to look effortless

Don't underestimate your own potential, don't underestimate your future. Everyone has a miracle that the world seems impossible, and it will be achieved with your strong efforts.

Efforts can only pass, desperately to be excellent!

Hard work and regret, which one is more painful?

You can only look effortless if you work very hard.

The road to success is not crowded at all. Many successes are embarrassing. Whether it is deep enough and fine enough in the direction of identification; many people can’t stand it at all; according to the diligence and effort of most people, it’s not up to the point. To the extent of talent.

When you want to do something, just work hard to do it.

The secret of success is not a secret at all, and that is to keep doing it. If you really work hard, you will find yourself much better than you think.

You have to endure the hardships of suffering, and believe that everything will go through the end of all efforts.

In the dark, my heart is bright, my dreams are not extinguished, and I am working hard.

You never know how hard others work.

What really determines a person's achievements is not talent, nor luck, but strict self-discipline and high-intensity.

Things you really like don't need to stick to it. I have to work hard all the time, and I have to struggle. In fact, most of them don’t really like what they are doing right now. Do you think Van Gogh thinks that painting needs to give yourself blood and tell yourself to stick to your teeth? Would you tell yourself to insist on eating every day and insist on playing?

How much effort have you made for what you want to do?

Life will not live up to our hard work every day. I hope that these sentences can inspire our hearts and realize our dreams.

Posted in Uncategorized | Tagged | 901 Comments

Comparison of application scenarios between HBase and Redis

HBase and Redis are similar in function. Both are nosql type databases. However, in the applicable scenario, there are still obvious differences between the two.

The following are based on multiple dimensions such as read and write performance, data type, data volume, deployment difficulty, data reliability, application scenarios, and a combination of the two.

Read and write performance:
HBase writes are slow to read, HBase's read time is usually a few milliseconds, and Redis's read time is usually tens of microseconds. The performance difference is very large.

type of data:
Both HBase and Redis support the KV type. But Redis supports richer types such as List and Set.

The amount of data:
The amount of data supported by Redis is usually limited by memory, and HBase does not have this limitation, and can store data that is much larger than the size of memory.

Easy to deploy:
HBase deployment relies on services such as hadoop and zookeeper, and Redis deployment is very simple.

Data reliability:
HBase uses WAL, which records the log and then writes the data. In theory, no data is lost. Redis uses asynchronous replication data, which may lose data when failover.

Application scenario:
HBase is suitable for persistent storage of big data, and Redis is more suitable for caching. If data loss is not tolerated, use HBase only; if you need a high-performance environment and can tolerate a certain amount of data loss, then you can consider using Redis.

The combination of the two:
HBase can be used to solidify data, that is, data storage. It is very suitable for him. Redis is suitable for caching. HBase+Redis can be used to implement data warehouse plus cache database, both speed and scalability.

Based on the above comparison, we can see. Both have their own areas of expertise, and there is no substitute for each other. Which service is selected specifically depends on the specific business scenario and the amount of data to select the most suitable solution.

Posted in service | Tagged , , | 2,557 Comments

Inspirational sentence about learning

I have collected some inspirational sentences about learning, and whenever I am slack, I will go and see. Can give yourself a lot of motivation.

  • Why can't you fight hard at the age you can still learn?

  • A little more, a little more observation, a little more learning.

  • Good days should be especially cherished, and bad days must learn to adapt.

  • Learning is a belief.

  • Philosophy of life, insight into the world, treatment of money, interpersonal relationships, effective learning, and doing things.

  • Even if you have the envy of everyone, the talents of the books and the inexhaustible wealth can not prove your strength. Because the heart is strong, it is truly powerful.

  • People with attitudes are good at self-study.

  • Keep righteous thoughts, do your best, keep the water flowing, the radar is on, and you are self-taught.

  • Reading is a shortcut to gain wisdom, become mature, learn to think, and understand human nature.

  • Make any choices, even if they are small, stop and think about it, learn to delay your desires.

  • Reading and listening to classes is not an active learning, but output (writing, teaching others, practice).

  • Learn more about several sports.

  • Learn to talk, learn to chat, learn to speak

  • Learning a new thing, the mood will be very good.

With the development of the times, lifelong learning has become a trend. I hope that these words will give us the motivation to learn for life.

Posted in learning | Tagged , | 443 Comments

Some inspirational sentences I collected

There are always climaxes and troughs in life, and inspirational sentences can give us strength when we are jealous. Here are some inspirational sentences I have collected, hoping to give courage to the undecided classmates.

  • All efforts are worthy of expectation, and every dream should be irrigated!

  • Very good principle: let go of the burden, don't force it, face the problem, and answer it.

  • What really makes a person mature is not that you have the ability to solve all problems, but that you have the courage to face this problem. When you really start to face these things and face him, this thing will slowly get better.

  • Be a hardcore youth: be tough inside, passionate about thinking, living hard, not convinced.

  • Each of us is afraid that we will do something wrong, and we will certainly do something wrong, but some things must be done, because doing is better than not doing it, we can only move forward in error.

  • Have a dream to chase, don't give up, don't be afraid to fall. Don't wait until you get old and think about it.

  • Whether it falls into the bottom or goes to the cloud, tomorrow will be a new day, and there is limitless possibilities.

The last sentence is my favorite sentence. Self-discipline is the most important tool for solving life problems, and the most important way to eliminate the pain of life. Self-discipline gives me freedom.

Posted in Uncategorized | Tagged | 906 Comments

Easy weight loss, indoor running skills

Running is a very good aerobic exercise. It is also very helpful for losing weight.

But in the winter, air pollution is usually heavier, and it takes a lot of courage to go out for a run.

In the hazy days, everyone can actually run at home.

This is indoor running.

Indoor running has many advantages over running outdoors.

1, indoor running, do not worry about the motor

When running outdoors, always pay attention to the traffic flow around the front, rear, left and right. Some motor vehicles or bicycles that do not comply with the regulations will cause us a lot of trouble.

But running indoors, there is no such worry.

2, indoor running, you can watch TV while running.

Running outdoors, for safety reasons, it is generally not recommended to listen to music with headphones.

Running indoors, don't say you can listen to audio, you can watch TV.

Watching TV while running, time passed quickly.

3, indoor running, not tired after running

Running outdoors, sometimes running farther. There is still a long way to go home. It looks very tired.

Run indoors and take a shower after running. Not very tired.

Say the advantages of so many indoor running, and then talk about some indoor running precautions.

First of all, indoor running should be raised, don’t squat

When running indoors, if your feet are squatting, it will bring a big impact to your knees. After a long time, it will damage the knee.

Be sure to keep your movements light. Don't use your strength.

Secondly, indoor running is best to wear shoes.

This is to protect our feet. It is best to wear running shoes with good cushioning for indoor running.

Finally, indoor running also monitors heart rate

For safety, we will bring a heart rate monitor or heart rate belt when we are running. Monitor your heart rate.

Although indoor exercise is not a big amount of exercise, for safety, it is best to bring your heart rate equipment and record your heart rate.

My own experience is that indoor running can also play a good exercise to lose weight.

Friends who can't go out for a run in the haze can try indoor running.

There must be surprises.

Posted in health | Tagged , | 1,594 Comments

Inspirational sentence about running

Running is a very good aerobic exercise. If you keep running for a long time, people's spirit and temperament will change significantly. The body will be healthier and people will become more confident. Many friends just heard about the benefits of running, but did not try. I highly recommend everyone to try and run. Will bring a different experience to your life.

Here are some of the inspirational sentences I have collected about running, and I share them with you.

———

As long as you stick to it, no matter whether you are running or living, there is no such thing as failure.

The miracle is not that I ran away. The miracle is that I have the courage to start.

As long as you are willing to change in order to become better, insist on doing the right thing, such as running, one day, you will meet yourself after growing up.

If you want to be strong, run!
If you want to be fit, run!
If you want to be smart, run!

Choose players who are easy to keep up with in their own line of sight, and then run and then go beyond.

I am not running for others, just running for myself.

Run and meet yourself better.

Run up, the mood will be very good.

Life is an endurance race, not a hundred meters sprint. The important thing is not how fast you run, but how far you can run.

When you grow up, there will always be one or two times, and you will run for the people you value.

--

I hope these sentences can help everyone and let everyone feel the encouragement of running. Run up to make your body healthier.

Posted in health | Tagged | 703 Comments