How to use GitHub Copilot: A guide for developers
Pics credit: blog post

How to use GitHub Copilot: A guide for developers

GitHub Copilot is a new service that provides code suggestions powered by OpenAI Codex, a large-scale language model trained on billions of lines of code. GitHub Copilot can help you write code faster and better, by suggesting whole lines or entire functions as you type, based on the context of your code and comments. GitHub Copilot can also answer natural language questions and generate code snippets based on your queries.

GitHub Copilot is currently available as a Visual Studio Code extension, but it also supports other popular IDEs like Azure Data Studio, JetBrains IDEs, Vim/Neovim, and Visual Studio. In this article, I will show you how to install and use GitHub Copilot in Visual Studio Code, and demonstrate some of its amazing capabilities.

Installing GitHub Copilot

To use GitHub Copilot, you need to have an active GitHub Copilot subscription. GitHub Copilot is free to use for verified students, teachers, and maintainers of popular open-source projects. For others, you can try GitHub Copilot for free with a one-time 30-day trial. After the free trial, you will need a paid subscription for continued use. For more information, see About billing for GitHub Copilot.

To use GitHub Copilot in Visual Studio Code, you need to have Visual Studio Code installed. You can download it from the Download Visual Studio Code - Mac, Linux, Windows.

To install the GitHub Copilot extension, follow these steps:

  • In the Visual Studio Code Marketplace, go to the GitHub Copilot - Visual Studio Marketplace and click Install.
  • A popup will appear, asking to open Visual Studio Code. Click Open Visual Studio Code.
  • In the Extension: GitHub Copilot tab in Visual Studio Code, click Install.

Visual Studio: Copilot Extension

  • If you have not previously authorized Visual Studio Code in your GitHub account, you will be prompted to sign in to GitHub in Visual Studio Code. If you have previously authorized Visual Studio Code for your account on GitHub, GitHub Copilot will be automatically authorized. If you don’t get the prompt to authorize, click the bell icon in the bottom panel of the Visual Studio Code window.
  • In your browser, GitHub will request the necessary permissions for GitHub Copilot. To approve these permissions, click Authorize Visual Studio Code.
  • To confirm the authentication, in Visual Studio Code, in the Visual Studio Code dialog box, click Open.

You have successfully installed the GitHub Copilot extension. You can now start using GitHub Copilot in your code editor.

Using GitHub Copilot

GitHub Copilot can suggest code for you as you type, and works well for various languages and frameworks, such as Python, JavaScript, TypeScript, React, Ruby, Java, C#, Go, and more. You can accept, reject, or modify the suggestions as you wish. You can also use keyboard shortcuts to cycle through different suggestions or accept the next word or line.

To see code suggestions from GitHub Copilot, simply start typing in your code editor. GitHub Copilot will show a grey placeholder for the suggested code, and a blue icon in the left margin. You can press the Tab key to accept the suggestion, or press Escape to dismiss it. You can also press Ctrl+Space to see a list of alternative suggestions, and use the arrow keys to navigate and select the one you want.

Here are some examples of how GitHub Copilot can suggest code for you:

  • If you want to write a function to reverse a string in Python, you can simply type def reverse_string(s): and press Tab. GitHub Copilot will suggest the following code:

Python

def reverse_string(s):
    # initialize an empty string
    reversed_s = ""
    # loop through the characters of s in reverse order
    for i in range(len(s) - 1, -1, -1):
        # append each character to the reversed string
        reversed_s += s[i]
    # return the reversed string
    return reversed_s        

  • If you want to write a React component that renders a button with a click handler, you can simply type function Button(props) { and press Tab. GitHub Copilot will suggest the following code:

function Button(props) {
    // define a function to handle the button click
    function handleClick() {
        // call the onClick prop function if it exists
        if (props.onClick) {
            props.onClick();
        }
    }
    // return the JSX element for the button
    return (
        <button
            // set the className prop if it exists
            className={props.className}
            // set the style prop if it exists
            style={props.style}
            // set the onClick handler to the handleClick function
            onClick={handleClick}
        >
            // render the children prop if it exists
            {props.children}
        </button>
    );
}
        

  • If you want to write a SQL query to get the average salary of employees by department, you can simply type SELECT and press Tab. GitHub Copilot will suggest the following code:

SQL

SELECT
    -- select the department name column
    department.name AS department,
    -- select the average salary column
    AVG(employee.salary) AS average_salary
-- from the employee table
FROM employee
-- join the department table on the department id
JOIN department ON employee.department_id = department.id
-- group by the department name
GROUP BY department.name
-- order by the average salary in descending order
ORDER BY average_salary DESC;
        

As you can see, GitHub Copilot can suggest code that is relevant, complete, and well-commented. However, you should always review, test, and debug the code that GitHub Copilot suggests, as it may not always be correct, optimal, or secure.

Chatting with GitHub Copilot

GitHub Copilot can also answer natural language questions and generate code snippets based on your queries. You can use the command palette or the prefix // to start a chat session with GitHub Copilot.

To chat with GitHub Copilot using the command palette, follow these steps:

  • Press Ctrl+Shift+P to open the command palette.
  • Type GitHub Copilot: Chat and press Enter.
  • Type your question or query and press Enter.
  • GitHub Copilot will respond with an answer or a code snippet, or ask for clarification if needed.

To chat with GitHub Copilot using the prefix //, follow these steps:

  • Type // in your code editor, followed by your question or query.
  • Press Enter to submit your question or query.
  • GitHub Copilot will respond with an answer or a code snippet, or ask for clarification if needed.

Here are some examples of how you can chat with GitHub Copilot:

  • If you want to ask GitHub Copilot to explain what a piece of code does, you can simply type // explain what this code does and paste the code below it. For example:

Python

// explain what this code does
def is_palindrome(s):
    # convert the string to lowercase
    s = s.lower()
    # remove all non-alphanumeric characters
    s = "".join(c for c in s if c.isalnum())
    # check if the string is equal to its reverse
    return s == s[::-1]
        

GitHub Copilot will respond with the following explanation:

Python

// This code defines a function named is_palindrome that takes a string as an argument and returns True if the string is a palindrome, or False otherwise. A palindrome is a word or phrase that is the same when read forward or backward, ignoring case and punctuation. For example, "racecar" and "Madam, I'm Adam" are palindromes.
// The function does the following steps:
// - It converts the string to lowercase using the lower() method, so that the comparison is case-insensitive.
// - It removes all non-alphanumeric characters from the string using a list comprehension and the isalnum() method, so that the punctuation is ignored.
// - It checks if the string is equal to its reverse using the slicing syntax [::-1], which returns a reversed copy of the string.
// - It returns the result of the comparison as a boolean value.
        

  • If you want to ask GitHub Copilot to write a code snippet for a specific task, you can simply type // write a code snippet to and describe the task. For example:

JavaScript

// write a code snippet to get the current date and time in JavaScript        

GitHub Copilot will respond with the following code snippet:

JavaScript

// One way to get the current date and time in JavaScript is to use the Date object, which represents a date and time value. You can create a new Date object with the current date and time by using the constructor without any arguments, like this:

let now = new Date();

// You can then use various methods of the Date object to get different parts of the date and time, such as the year, month, day, hour, minute, second, etc. For example, to get the current year, you can use the getFullYear() method, like this:

let year = now.getFullYear();

//        

For reference to more prompts to play around with GitHub Copilot head over to the link: https://drive.google.com/file/d/1zPbZ-tNH-g1eyBzQwUJtawXes3d6nejw/view?usp=sharing

Dan Balter

Father // Executive // Biz Dev & Partnerships // Investor

1 年

The integration of GitHub Copilot across various IDEs is a testament to AI tools' flexibility and user-centric design in software development. It's exciting to see how this AI assistant can streamline coding tasks and empower developers to tackle complex projects with newfound efficiency.

要查看或添加评论,请登录

Sourav Bera的更多文章

社区洞察

其他会员也浏览了